【问题标题】:ggplot geom_line to date axis not workingggplot geom_line 到日期轴不起作用
【发布时间】:2015-06-21 23:32:21
【问题描述】:

我有几个类似于https://www.dropbox.com/s/j9ihawgfqwxmkgc/pred.csv?dl=0的数据集

从 CSV 加载它们然后绘图工作正常

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

但是当我想使用 GGPLOT 将这些数据预测点绘制到一个图中以将它们与原始点进行比较时,例如:

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

这个命令

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

产生以下错误:

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

但由于第一个 plot(predictions$date, predictions$pct50) 处理数据,我不明白出了什么问题。

编辑

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

编辑 2

我改这个

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

错误改为:

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

所以我认为How to deal with "data of class uneval" error from ggplot2?(见 cmets)的提示是一个好主意,但情节仍然不起作用。

【问题讨论】:

  • ?geom_line 显示第一个参数是mapping = NULL。尝试明确说明data = predictions
  • This answer 类似
  • 当然——请看编辑
  • 谢谢你@tospig - 看到edit2你的提示进入了正确的方向,但情节仍然不起作用
  • 你的predictions$date 是一个字符向量,当使用as.numeric 时它会引入NAs。如果你想要数字,你可能需要as.numeric(as.Date(predictions$date), format="%Y%m%d")

标签: r ggplot2 line


【解决方案1】:

您的第一个问题(编辑 2)是因为 ?geom_line 使用 mapping=NULL 作为第一个参数,所以您需要明确声明第一个参数是 data

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

similar question

您的第二个问题是因为您的predictions$date 是一个字符向量,并且在使用 as.numeric 时它引入了NAs。如果您想要数字,则需要先将其格式化为日期,然后将其转换为数字

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-17
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    相关资源
    最近更新 更多