如何将垂直 geom_vline 设置为课程日期的 x 轴? [英] How to get a vertical geom_vline to an x-axis of class date?

查看:28
本文介绍了如何将垂直 geom_vline 设置为课程日期的 x 轴?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使我在 POSIXctgeom_vline 的 google 组中找到了 Hadley 的帖子,我也无法完成.例如,我有一个时间序列,并想为 1998、2005 和 2010 年绘制一条垂直线.我尝试使用 ggplotqplot 语法,但我仍然看不到垂直线,或者在第一个垂直网格处绘制了垂直线并且整个系列都被移动了右边有点奇怪.

Even though I found Hadley's post in the google group on POSIXct and geom_vline, I could not get it done. I have a time series from and would like to draw a vertical line for years 1998, 2005 and 2010 for example. I tried with ggplot and qplot syntax, but still I either see no vertical line at all or the vertical line is drawn at the very first vertical grid and the whole series is shifted somewhat strangely to the right.

gg <- ggplot(data=mydata,aes(y=somevalues,x=datefield,color=category)) +
      layer(geom="line")
gg + geom_vline(xintercept=mydata$datefield[120],linetype=4)
# returns just the time series plot I had before, 
# interestingly the legend contains dotted vertical lines

我的日期字段的格式为1993-07-01",属于 Date 类.

My date field has format "1993-07-01" and is of class Date.

推荐答案

Try as.numeric(mydata$datefield[120]):

gg + geom_vline(xintercept=as.numeric(mydata$datefield[120]), linetype=4)

一个简单的测试示例:

library("ggplot2")

tmp <- data.frame(x=rep(seq(as.Date(0, origin="1970-01-01"),
                            length=36, by="1 month"), 2),
                  y=rnorm(72),
                  category=gl(2,36))

p <- ggplot(tmp, aes(x, y, colour=category)) +
     geom_line() +
     geom_vline(xintercept=as.numeric(tmp$x[c(13, 24)]),
                linetype=4, colour="black")
print(p)

这篇关于如何将垂直 geom_vline 设置为课程日期的 x 轴?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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