【问题标题】:Understanding dates a plotting with ggplot2 in R了解日期在 R 中使用 ggplot2 进行绘图
【发布时间】:2015-11-23 11:30:20
【问题描述】:

我有一个名为 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

使用 ggplot2

我只想用 ggplot2line char 中绘制 dateeliter,代码如下:

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

但是,它返回与类相关的错误: 错误:ggplot2 不知道如何处理数字类的数据

我尝试创建一个data.frame,但它仍然返回错误:

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

错误:ggplot2 不知道如何处理 Date 类的数据

有情节

我已经设法用 plot() 函数做到了:

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

而且效果很好!但我不能用 ggplot 做到这一点。

谁能帮帮我?

非常感谢。

【问题讨论】:

  • x_date添加到您的数据框后,仍然传递ggplot整个数据框,即ggplot(d, aes(...))而不是ggplot(d$xdate, aes(...))。错误消息告诉您,您正在向 ggplot 传递一个日期向量,它需要一个完整的数据框。
  • 另外,不要在aes() 中使用$。具有data 参数的 ggplot 的要点是您不要不断重新输入数据框。 ggplot(d, aes(x = xdate, y = yeliter)) + geom_line().
  • 好的@Gregor!非常感谢!

标签: r date csv plot ggplot2


【解决方案1】:

像这样添加+ 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()

【讨论】:

    猜你喜欢
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    • 2018-08-31
    • 2023-03-24
    • 1970-01-01
    • 2022-08-13
    • 1970-01-01
    相关资源
    最近更新 更多