我正在尝试绘制一些价格与日期的关系图。大约有10k行数据。日期范围为 ~ 7/1/2008 - 12/1/2011。我希望能够为每年 年创建一个带有以下刻度的自定义 x 轴:
1) 在 1/1 有 YYYY(即 2011
)
2) 在 4/1 有月份的缩写(即 Apr
)
3) 在 7/1 有月份的缩写(即 Jul
)
4) 在 10/1 有月份的缩写(即 Oct
)
这是对数据的描述:
> head(as.POSIXct(rs4p[,3]))
[1] "2008-06-30 20:00:00 EDT" "2008-06-30 20:00:00 EDT"
[3] "2008-06-30 20:00:00 EDT" "2008-06-30 20:00:00 EDT"
[5] "2008-06-30 20:00:00 EDT" "2008-06-30 20:00:00 EDT"
> head((rs4p[,3]))
[1] "2008-07-01" "2008-07-01" "2008-07-01" "2008-07-01" "2008-07-01"
[6] "2008-07-01"
> min((rs4p[,3]))
[1] "2008-07-01"
> max((rs4p[,3]))
[1] "2011-12-08"
> class((rs4p[,3]))
[1] "Date"
更新:
我忘记的另一件事是,当图表完成后,我想在图表上放置一个 grid()
。有没有办法让网格线与年刻度相对应?
最佳答案
文森特先得到它,但这是我的动物园版本
library(zoo)
my.ts <-zoo(0:1000,as.Date("2000-01-01")+0:1000)
plot(my.ts, xaxt="n")
years <-index(my.ts)[format(index(my.ts),"%m-%d") %in% "01-01"]
other.quarters <- index(my.ts)[ format(index(my.ts), "%m-%d") %in% c("04-01", "07-01","10-01")]
axis.Date(1, at=years, label=format(years,"%y"))
axis.Date(1, at=other.quarters, label=format(other.quarters, "%b"))
更新:以下是添加网格线的方法:
grid(nx=NA, ny=NULL)
abline(v=c(years, other.quarters),col = "lightgray", lty = "dotted", lwd = par("lwd"))
关于R 如何使用日期创建自定义 x 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8919513/