ggplot geom_line to date axis not working

6.2k Views Asked by At

I have several data-sets similar to https://www.dropbox.com/s/j9ihawgfqwxmkgc/pred.csv?dl=0

Loading them from CSV and then plotting works fine

predictions$date <- as.Date(predictions$date)
plot(predictions$date, predictions$pct50)

But when I want to use GGPLOT to draw these data predicted points into a plot to compare them with the original points like:

p = ggplot(theRealPastDataValues,aes(x=date,y=cumsum(amount)))+geom_line()

This command

p + geom_line(predictions, aes(x=as.numeric(date), y=pct50))

generates the following error:

ggplot2 doesn't know how to deal with data of class uneval

But as the first plot(predictions$date, predictions$pct50) works with the data I do not understand what is wrong.

Edit

dput(predictions[1:10, c("date", "pct50")])
structure(list(date = c("2009-07-01", "2009-07-02", "2009-07-03", 
"2009-07-04", "2009-07-05", "2009-07-06", "2009-07-07", "2009-07-08", 
"2009-07-09", "2009-07-10"), pct50 = c(4276, 4076, 4699.93, 4699.93, 
4699.93, 4699.93, 4664.76, 4627.37, 4627.37, 4627.37)), .Names = c("date", 
"pct50"), row.names = c(NA, 10L), class = "data.frame")

Edit 2

I change this

p + geom_line(data = predictions, aes(x=as.numeric(date), y=pct50))

and the error changed to:

Invalid input: date_trans works with objects of class Date only
Zusätzlich: Warning message:
In eval(expr, envir, enclos) : NAs created

so I think the hint to How to deal with "data of class uneval" error from ggplot2? (see comments) was a good Idea, bit still the plot does not work.

1

There are 1 best solutions below

0
On BEST ANSWER

Your first issue (Edit 2) is because ?geom_line uses mapping=NULL as the first argument, so you need to explicitely state the first argument is data

p + geom_line(data = predictions, aes(x=as.numeric(date), y=pct50))

similar question

Your second issue is because your predictions$date is a character vector, and when using as.numeric it introduces NAs. If you want numerics you need to format it as a date first, then convert it to numeric

as.numeric(as.Date(predictions$date), format="%Y%m%d")