How to format axes in R, year and months
I have the following dataset
1890 mar 0.4
1890 apr 0.8
1890 may 1.0
...
1989 jan 0.2
1989 feb 0.4
1989 mar 0.5
How can I make a line plot in R with on the x-axis the year, displayed every 5 years?
My problem is not so much making the plot, but getting to disp开发者_开发知识库lay only the years I want, and place them on the beginning of that year. So I don't want a tick on April but on January.
This should get you started:
# create some data
set.seed(1)
tmp <- seq(as.POSIXct("1890-03-01", tz="GMT"),
as.POSIXct("1920-03-01", tz="GMT"),
by="month")
df <- data.frame(date=tmp,
val=rnorm(length(tmp)))
# plot data
plot(df$date, df$val, xaxt="n")
tickpos <- seq(as.POSIXct("1890-01-01", tz="GMT"),
as.POSIXct("1920-01-01", tz="GMT"),
by="5 years")
axis.POSIXct(side=1, at=tickpos)
You get what rcs (correctly !) suggested by default using zoo as plot with lines and the same axis:
R> library(zoo)
R> zdf <- zoo(df$val, order.by=df$date)
R> plot(zdf)
R>
The help(plot.zoo)
examples show to do fancier date indexing, essentially what rcs showed you but with an additional formatting via, say,
R> fmt <- "%Y-%m" ## year-mon
R> txt <- format(index(zdf), fmt)
R> plot(zdf, xaxt='n')
R> axis(side=1, at=index(zdf), lab=txt)
R>
If you subset at
and lab
you get fewer ticks too.
精彩评论