如何获得垂直的geom_vline到类日期的x轴? [英] How to get a vertical geom_vline to an x-axis of class date?

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

问题描述

即使我发现Hadley在Google群组中的 POSIXct geom_vline 的帖子,我无法完成。我有一个时间序列,并希望在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)) +
     layer(geom="line") +
     geom_vline(aes(xintercept=as.numeric(x[c(13, 24)])),
                linetype=4, colour="black")
print(p)

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

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