1

I have a series of data which I want to plot over a date x-axis

ed <- data.frame(election.date = as.Date(mdy(c("November 6, 2012",
                                               "November 4, 2008",
                                               "November 2, 2004",
                                               "November 7, 2000",
                                               "November 5, 1996",
                                               "November 3, 1992",
                                               "November 8, 1988",
                                               "November 6, 1984"))),
                  num = rnorm(8))

If I just plotted the points, everything works

ggplot(ed) + geom_point(aes(x = election.date, y = num))

enter image description here

but if I add vertical lines for each of the points, I get

ggplot(ed) + 
     geom_point(aes(x = election.date, y = num))  +
     geom_vline(aes(x = election.date))  

enter image description here

Rather than drawing the 8 lines at their proper dates, we get a single line at the start of Unix time.

A solution provided elsewhere on SO for a similar problem is adapted here as

ggplot(ed) + 
     geom_point(aes(x = election.date, y = num))  +
     geom_vline(aes(x = as.numeric(election.date)))

but this elicits the error:

Error: Invalid input: date_trans works with objects of class Date only

how can I draw multiple vertical lines with dates located in a data frame?

Community
  • 1
  • 1
tomw
  • 3,114
  • 4
  • 29
  • 51

1 Answers1

1

Not sure why you're getting the errors that you are, but hopefuly this fixes it (note the xintercept in the geom_vline instead of x):

ggplot(ed) + 
     geom_point(aes(x = election.date, y = num))  +
     geom_vline(aes(xintercept = as.numeric(election.date))) 
GregF
  • 1,292
  • 11
  • 14