【发布时间】:2017-09-25 10:42:20
【问题描述】:
我尝试在图表中包含一条垂直线,x 轴为日期。线的位置应由某个日期确定。但是,我无法通过日期本身来控制位置,而只能通过数据集中日期的位置/行来控制。 由于其他行可能会在稍后的时间点进入数据集,因此我寻找使用日期而不是其位置的解决方案。
这里有一些虚拟数据来说明我的问题和方法:
library(ggplot2)
#Setting up of Dummy Data
Dummy_date<-seq(as.Date("2017-01-01"),as.Date("2017-06-01"),by="days")
Dummy_data<-seq(1:152)
Dummy_df<-as.data.frame(cbind(Dummy_date,Dummy_data))
names(Dummy_df[1])<-"Date"
names(Dummy_df[2])<-"Data"
#Format Dates
Dummy_df$Dummy_date<-as.POSIXct(Dummy_date)
#Does not work but is the desired approach
ggplot(Dummy_df)+
geom_point(mapping=aes(x=Dummy_date,y=Dummy_data))+
geom_vline(aes(xintercept=as.numeric(as.Date("2017-04-01"))),type=4,col="red")
#Works but I do not like the fixed position[91] in the dataset. Line 91 contains the relevant date
ggplot(Dummy_df)+
geom_point(mapping=aes(x=Dummy_date,y=Dummy_data))+
geom_vline(aes(xintercept=as.numeric(Dummy_date[91])),type=4,col="red")
提前致谢
【问题讨论】: