How to get vertical geom_vline to x-axis of class date?

Although I found a Hadley entry in the google group on POSIXct and geom_vline , I was not able to do it. I have time series and would like to draw a vertical line during the years 1998, 2005 and 2010, for example. I tried using the syntax ggplot and qplot , but still I either do not see the vertical line at all, or the vertical line is drawn in the very first vertical grid, and the whole series is shifted somewhat strangely to the right.

 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 

My date field is in the format "1993-07-01" and has a Date class.

+87
date r time-series ggplot2
Mar 22 '11 at 9:01
source share
3 answers

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

 gg + geom_vline(xintercept=as.numeric(mydata$datefield[120]), linetype=4) 

A simple example:

 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) 

geom_vline example plot

+125
Mar 22 '11 at 13:15
source share

You can also do geom_vline(xintercept = as.numeric(as.Date("2015-01-01")), linetype=4) if you want the line to stay in place regardless of whether your date is at 120- st line.

+17
Feb 14 '17 at 23:07 on
source share

I tried the following two examples:

 g4 <- g3 + geom_vline(aes(xintercept = as.Date(c("2015-04-09"))), col = "black", lwd=1, lty=2) g4 <- g3 + geom_vline(aes(xintercept = as.numeric(dt[301])), col = "black", lwd=1, lty=2) 

However, I cannot get multiple line numbers for input. If I use dt [92, 301, 475]. I get an error saying that the length should be either 1 or equal to the total number of lines.

0
May 27 '19 at 8:29 am
source share



All Articles