0

I have a CSV file called gdata.csv, with data like:

id,date,totKm,eLiter,euros,liters,km
1,24-04-2010,23678,1.180,42.00,35.59,450
2,16-05-2010,24058,1.200,43.00,35.83,380
3,27-05-2010,24488,1.160,44.00,37.93,430
4,12-06-2010,24960,1.180,45.00,38.14,472

With ggplot2

I just want to plot date and eliter in a line char with ggplot2, with this code:

x_date <- as.Date(gdata$date, format = "%d-%m-%Y")
ggplot(eliter, aes(x_date, eliter)) + geom_line()

But, it returns this error related with the class: Error: ggplot2 doesn't know how to deal with data of class numeric

I have tried to make a data.frame but it stills returns the error:

d <- data.frame(xdate = x_date, yeliter=gdata$eLiter)
ggplot(d$xdate, aes(d$xdate, d$yeliter)) + geom_line()

Error: ggplot2 doesn't know how to deal with data of class Date

With plot

I have managed to do this with plot() function:

plot(gdata$eLiter~as.Date(gdata$date, "%d-%m-%Y"), type = "s", xlab="Date",ylab="€/Liter", main="€/liter trend", col='blue')

And it works fine! But I can not do it with ggplot.

Could anyone help me?

Thank you very much.

3
  • 1
    After adding x_date to your data frame, still pass ggplot the entire data frame, that is ggplot(d, aes(...)) not ggplot(d$xdate, aes(...)). The error message is telling you that you're passing ggplot a single vector of dates where it's expecting a full data frame. Commented Aug 28, 2015 at 18:12
  • Also, don't use $ inside aes(). The point of ggplot having a data argument is that you don't keep re-typing the data frame. ggplot(d, aes(x = xdate, y = yeliter)) + geom_line(). Commented Aug 28, 2015 at 18:14
  • Ok @Gregor! Thank you very much! Commented Aug 28, 2015 at 18:19

1 Answer 1

1

Add + scale_x_date() like this:

Lines <- "id,date,totKm,eLiter,euros,liters,km
1,24-04-2010,23678,1.180,42.00,35.59,450
2,16-05-2010,24058,1.200,43.00,35.83,380
3,27-05-2010,24488,1.160,44.00,37.93,430
4,12-06-2010,24960,1.180,45.00,38.14,472"

DF <- read.csv(text = Lines)
DF$date <- as.Date(DF$date, "%d-%m-%Y")

library(ggplot2)
ggplot(DF, aes(date, eLiter)) +
  geom_line() +
  scale_x_date()

screenshot

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.