简体   繁体   English

如何格式化R,年和月的轴

[英]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? 如何在每年5年显示的年份x轴上绘制R线图?

My problem is not so much making the plot, but getting to display 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. 所以我不想在4月份但在1月份打勾。

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: 你可以得到rcs(正确!)默认情况下使用zoo建议的线条和相同的轴:

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, help(plot.zoo)示例显示做更好的日期索引,基本上是rcs向您展示但是通过其他格式化,例如,

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. 如果你at lab那么你也会得到更少的蜱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM