【问题标题】:How to get a vertical geom_vline to an x-axis of class date?如何将垂直 geom_vline 获取到课程日期的 x 轴?
【发布时间】:2011-07-20 07:37:31
【问题描述】:

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

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 类。

【问题讨论】:

  • 您可以添加几行数据框,以便我们尝试您的示例吗?

标签: r date ggplot2 time-series


【解决方案1】:

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

【讨论】:

  • 我发现 'as.numeric()' 实际上很难找到!谢谢。
  • 我想知道geom_vline(aes(xintercept=as.numeric(x[c(13, 24)])), linetype=4, colour="black") 是否会更惯用,即使用aes 而不是tmp$
  • 此解决方案不再有效。代码产生```错误:试图创建没有统计的层。运行rlang::last_error() 看看哪里出错了。``'
【解决方案2】:

如果您希望线路保持原位,无论您的日期是否在第 120 行,您也可以使用 geom_vline(xintercept = as.numeric(as.Date("2015-01-01")), linetype=4)

【讨论】:

  • 在我的机器上(带有 R 3.2.2 和 ggplot 1.0.1 的 Win10),我必须将日期强制转换为 POSIXct 以使其正确对齐:as.POSIXct(as.Date(c("2016-12-01","2017-02-01")))
  • 谢谢你,Jthorpe.. 这是唯一对我有用的版本
【解决方案3】:

根据您将“日期”列传递给aes 的方式,as.numericas.POSIXct 有效:

library(ggplot2)

  1. 使用aes(as.Date(Dates),...)

    ggplot(df, aes(as.Date(Dates), value)) +
       geom_line() +
       geom_vline(xintercept = as.numeric(as.Date("2020-11-20")), 
                  color = "red", 
                  lwd = 2) 
    
  2. 使用aes(Dates, ...)

    ggplot(df, aes(Dates, value)) +
       geom_line() +
       geom_vline(xintercept = as.POSIXct(as.Date("2020-11-20")), 
                  color = "red", 
                  lwd = 2) 
    

【讨论】:

    【解决方案4】:

    as.numeric 对我有用

    ggplot(data=bmelt)+
      geom_line(aes(x=day,y=value,colour=type),size=0.9)+
      scale_color_manual(labels = c("Observed","Counterfactual"),values = c("1","2"))+
      geom_ribbon(data=ita3,aes(x=day, 
          y=expcumresponse, ymin=exp.cr.ll,ymax=exp.cr.uu),alpha=0.2) +
      labs(title="Italy Confirmed cases",
            y ="# Cases ", x = "Date",color="Output")+
      geom_vline(xintercept = as.numeric(ymd("2020-03-13")), linetype="dashed", 
                    color = "blue", size=1.5)+
      theme_minimal()
    

    code output

    【讨论】:

      猜你喜欢
      • 2020-02-05
      • 2017-09-25
      • 2017-02-11
      • 1970-01-01
      • 1970-01-01
      • 2011-10-29
      • 1970-01-01
      相关资源
      最近更新 更多