# [R] How to plot several years data with date information by months?

Marc Girondot marc_grt at yahoo.fr
Sat Apr 6 14:44:09 CEST 2013

```Le 06/04/13 10:00, ZhaoXing a écrit :
> Hi, all
>
> I have a medium sized data, 6 years. Each observation is a case with a date variable, such as '2004-08-02'.
> Some of the months didn't occur a case.
> I want to plot the 6 years data by month, and the Y_axis is the freqency of cases for each month, meaning 12*6=72 bars or points in the figure.
> I though of a method, 1st, using the months function, then ploting. But I need to assign zero to the months without case. And a lot of other manipulations.
> Is there any simpler way to complete this? or just a simple function exists?
>
>
> ZhaoXing
>
Sincerely
Marc

# I generate dummy data
x <- seq(from=as.Date("2000-01-01"), to=as.Date("2006-12-31"), by="1 day")
y <- sample(0:10, 2557, replace=TRUE)
t <- y + sample(5:20, 2557, replace=TRUE)
dt <- data.frame(d = x, obs = y, total=t)
# I erase some data; sometimes full month is erased
dt <- dt[c(20:156, 300:900, 1200:2557),]

# I begin here
# I generate a variable with all the months
x2 <- seq(from=as.Date("2000-01-01"), to=as.Date("2006-12-31"), by="1
month")

# I add this variable with all the months to the available data to have
information also for missing months
dt <- rbind(dt, data.frame(d=x2,
obs = rep(NA, length(x2)), total=rep(NA, length(x2))))

# I sum month per month
o1 <- with(dt, rowsum(obs, format(d,"%Y-%m"), na.rm=TRUE))
o2 <- with(dt, rowsum(total, format(d,"%Y-%m"), na.rm=TRUE))

# If total for a month is 0, I replace it with NA
o1[o2==0] <- NA
o2[o2==0] <- NA

# proportion
y <- o1/o2

# plot
plot(x2, y, bty="n", type="p", xaxt="n", las=1)

axis(1, at=seq(from=as.Date("2000-01-01"), to=as.Date("2006-12-31"),
by="1 month"), label=FALSE)
axis(1, at=seq(from=as.Date("2000-01-01"), to=as.Date("2006-12-31"),
by="1 year"), lwd.ticks=2, label=FALSE, lwd=0)
axis(1, at=seq(from=as.Date("2000-07-01"), to=as.Date("2006-12-31"),
by="1 year"), lwd.ticks=0, label=c(2000:2006), lwd=0)

--
__________________________________________________________
Marc Girondot, Pr

Laboratoire Ecologie, Systématique et Evolution
Equipe de Conservation des Populations et des Communautés
CNRS, AgroParisTech et Université Paris-Sud 11 , UMR 8079
Bâtiment 362
91405 Orsay Cedex, France

Tel:  33 1 (0)1.69.15.72.30   Fax: 33 1 (0)1.69.15.73.53
e-mail: marc.girondot at u-psud.fr
Web: http://www.ese.u-psud.fr/epc/conservation/Marc.html
Skype: girondot

```