如何将垂直 geom_vline 获取到课程日期的 x 轴? [英] How to get a vertical geom_vline to an x-axis of class date?
问题描述
即使我在 POSIXct
和 geom_vline
的 google 小组中找到 Hadley 的帖子,我还是无法完成.例如,我有一个时间序列,并想为 1998 年、2005 年和 2010 年画一条垂直线.我尝试使用 ggplot
和 qplot
语法,但我仍然看不到垂直线,或者在第一个垂直网格处绘制垂直线并且整个系列被移动右边有点奇怪.
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
.
推荐答案
试试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屋!