R如何使用日期创建自定义x轴 [英] R how to create custom x-axis with dates

查看:45
本文介绍了R如何使用日期创建自定义x轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试绘制一些价格与日期的关系图.大约有 10k 行数据.日期范围为 ~ 7/1/2008 - 12/1/2011.我希望能够为每年创建一个带有以下刻度的自定义 x 轴:

I'm trying to plot some prices vs dates. There are about 10k lines of data. The dates are a range from ~ 7/1/2008 - 12/1/2011. I'd like to be able to create a custom x-axis with the following ticks on it for each year:

1) 在 1/1 处有 YYYY(即 2011)

1) at 1/1 have the YYYY (ie 2011)

2) 在 4/1 有月份的缩写(即 Apr)

2) at 4/1 have the abbreviation of the month (ie Apr)

3) 在 7/1 有月份的缩写(即 Jul)

3) at 7/1 have the abbreviation of the month (ie Jul)

4) 在 10/1 有月份的缩写(即 Oct)

4) at 10/1 have the abbreviation of the month (ie 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().有没有办法让网格线与年份刻度相对应?

One other thing I forgot is that when the graph is done I'd like to put a grid() over the plot. Is there a way to make the grid lines correspond to the year ticks?

推荐答案

Vincent 先得到它,但这是我与 zoo 的版本

Vincent got it first, but here's my version with zoo

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"))

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

UPDATE: Here's how to add gridlines:

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

这篇关于R如何使用日期创建自定义x轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆