如何将一个垂直geom_vline转换为类日期的x轴?

Mat*_*ert 93 r date time-series ggplot2

即使我发现哈德利对谷歌的论坛中发帖POSIXctgeom_vline,我无法完成它.我有一个时间序列,并希望绘制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
Run Code Online (Sandbox Code Playgroud)

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

rcs*_*rcs 129

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

gg + geom_vline(xintercept=as.numeric(mydata$datefield[120]), linetype=4)
Run Code Online (Sandbox Code Playgroud)

一个简单的测试示例:

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)
Run Code Online (Sandbox Code Playgroud)

geom_vline示例图

  • 如果这仍然不起作用,请添加scale_x_date() (5认同)
  • 我想知道`geom_vline(aes(xintercept = as.numeric(x [c(13,24)])),linetype = 4,color ="black")`是否会更加惯用,即使用`aes`代替`TMP $`. (2认同)
  • 该解决方案不再有效。代码产生``错误:尝试创建没有统计数据的图层。运行 `rlang::last_error()` 以查看错误发生的位置。``' (2认同)

D.H*_*ley 20

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

  • 在我的机器上(Win10与R 3.2.2和ggplot 1.0.1),我必须强制日期到POSIXct以使其正确对齐:`as.POSIXct(as.Date(c("2016-12-01") "2017年2月1日")))` (7认同)

mgr*_*und 7

根据您将“日期”列传递给 的方式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) 
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用aes(Dates, ...)

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