R 如何使用日期创建自定义 x 轴

标签 r plot

我正在尝试绘制一些价格与日期的关系图。大约有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"))

enter image description here

更新:以下是添加网格线的方法:

grid(nx=NA, ny=NULL)
abline(v=c(years, other.quarters),col = "lightgray", lty = "dotted", lwd = par("lwd"))

enter image description here

关于R 如何使用日期创建自定义 x 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8919513/

相关文章:

css - 使用和不使用 shiny 运行时,使用 rmarkdown ioslides 解决不同的 CSS 行为

r - R中的分箱时间数据

r - 如何在函数中编写 facet_wrap (ggplot2)

python - 如何在 Pandas 中的 "day period"上覆盖数据以进行绘图

python - Matplotlib colorbar 移动第二个 x 轴

python - imshow 带有整数轴标签的图

R 段无法处理透明度?

r - 使用 ggsave 和 Rscript 时如何阻止 R 创建空的 Rplots.pdf 文件

r - R 中的温度曲线

r - R中绘图函数中的45度线