我想要一个时间序列图,在某个时间点插入一条垂直线.我的数据从1990年1月开始.当我使用ggplot2时,垂直线被推到范围之外,而不是在期望的点.
下面的代码将显示正在发生的事情,但会显示随机生成的数据.任何帮助表示赞赏!
library(ggplot2) library(zoo) library(reshape) library(epitools) ##Generate Price Variables NormalPrices = as.data.frame(matrix(rnorm(300*3, mean=50, sd=10), ncol=3)) rownames(NormalPrices) = paste("sample", 1:300, sep="") colnames(NormalPrices) = paste("Price", 1:3, sep="") ##Assign as Time Series Data datt=ts(NormalPrices,start=c(1990,1), frequency=12) View(datt) time1=time(datt) time1=as.month(time1) time1=time1$dates datt=melt(data.frame(time1, datt),id.vars="time1") ## Plot P=ggplot((datt), aes(time1, value)) + geom_line() +facet_grid(variable ~ .)+ ggtitle("Level Prices") P + geom_vline(xintercept = 2001-04-01,colour="black", linetype = "longdash")+ theme_bw()+ theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"))
问题是,你的date("2001-04-01"
)没有正确转换.您可以调试此类问题,例如使用
> class("2001-04-01") [1] "character"
哪个与你的班级不匹配data.frame
(哪个Date
)
>str(datt) 'data.frame': 900 obs. of 3 variables: $ time1 : Date, format: "1990-01-01" "1990-02-01" "1990-03-01" "1990-04-01" ... $ variable: Factor w/ 3 levels "Price1","Price2",..: 1 1 1 1 1 1 1 1 1 1 ... $ value : num 52.1 46 46.3 50.7 64.6 ...
尝试首先将character
-Array转换为日期:
date <- as.Date("2001-04-01", format="%Y-%m-%d") gg <- ggplot((datt), aes(time1, value)) + geom_line() + facet_grid(variable ~ .)+ ggtitle("Level Prices") gg + geom_vline(xintercept = as.numeric(date), linetype=4) + theme_bw()+ theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"))
结果是: