4

I want a time-series plot with a vertical line inserted at some time point. My data spans from 1990 January onward. When I use ggplot2, the vertical line is pushed outside of the range, and not at the desired point.

The code below will show what's happening, but on randomly generated data. Any help is appreciated!

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

plot

agold
  • 6,140
  • 9
  • 38
  • 54
Prasanna S
  • 353
  • 1
  • 10

1 Answers1

6

Problem is, that your date ("2001-04-01") isn't converted correctly. You can debug issues like this e.g. using

> class("2001-04-01")
[1] "character"

which doesn't match your class from the data.frame (which is 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 ...

try converting the character-Array into a date first:

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

results in:

enter image description here

Boern
  • 7,233
  • 5
  • 55
  • 86