简体   繁体   English

了解日期与R中的ggplot2绘图

[英]Understanding dates a plotting with ggplot2 in R

I have a CSV file called gdata.csv , with data like: 我有一个名为gdata.csv的CSV文件,其数据如下:

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 使用ggplot2

I just want to plot date and eliter in a line char with ggplot2 , with this code: 我只是想绘制dateeliterGGPLOT2 行字符 ,使用此代码:

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 但是,它返回与该类相关的错误:错误:ggplot2不知道如何处理数字数值的数据

I have tried to make a data.frame but it stills returns the error: 我试图做一个data.frame但它仍然返回错误:

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 错误:ggplot2不知道如何处理日期类的数据

With plot 有剧情

I have managed to do this with plot() function: 我设法用plot()函数做到这一点:

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. 但是我不能用ggplot做到这一点。

Could anyone help me? 有人可以帮我吗?

Thank you very much. 非常感谢你。

Add + scale_x_date() like this: 像这样添加+ scale_x_date()

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

屏幕截图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM