Mat*_*ert 93 r date time-series ggplot2
即使我发现哈德利对谷歌的论坛中发帖POSIXct和geom_vline,我无法完成它.我有一个时间序列,并希望绘制1998年,2005年和2010年的垂直线.我尝试使用ggplot和qplot语法,但我仍然看不到垂直线,或者在第一个垂直网格上绘制垂直线,整个系列在右边有点奇怪地移动.
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)

D.H*_*ley 20
geom_vline(xintercept = as.numeric(as.Date("2015-01-01")), linetype=4)如果您希望线路保持在原位,无论您的日期是否在第120行,您也可以这样做.
根据您将“日期”列传递给 的方式aes,或者as.numeric或as.POSIXct有效:
library(ggplot2)
使用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)
使用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)