你在R中可能遇到的一个错误是:
Error: ggplot2 doesn't know how to deal with data of class uneval
这个错误通常发生在你试图使用ggplot2一次绘制两个数据框架,但在geom_line()函数中没有使用数据参数。
本教程准确地分享了如何修复这个错误。
如何重现该错误
假设我们在R中拥有两个数据框,显示在不同日子的特定时间内的销售数量:
#create first data frame
df <- data.frame(date=c(1, 1, 1, 2, 2, 2, 3, 3, 3),
hour=c(1, 2, 3, 1, 2, 3, 1, 2, 3),
sales=c(2, 5, 7, 5, 8, 12, 10, 14, 13))
#view data frame
head(df)
date hour sales
1 1 1 2
2 1 2 5
3 1 3 7
4 2 1 5
5 2 2 8
6 2 3 12
#create second data frame
df_new <- data.frame(date=c(4, 4, 4, 5, 5, 5),
hour=c(1, 2, 3, 1, 2, 3),
sales=c(12, 13, 19, 15, 18, 20))
#view data frame
head(df_new)
date hour sales
1 4 1 12
2 4 2 13
3 4 3 19
4 5 1 15
5 5 2 18
6 5 3 20
现在,假设我们试图创建一个折线图来显示按天和小时分组的销售额,对第一个数据框使用蓝色,对第二个数据框使用红色:
library(ggplot2)
#attempt to create line chart
ggplot(df, aes(x=hour, y=sales, group=date)) +
geom_line(color='blue') +
geom_line(df_new, aes(x=hour, y=sales, group=date), color='red')
Error: ggplot2 doesn't know how to deal with data of class uneval
我们收到一个错误,因为我们在第二个geom_line()函数中没有使用数据参数。
如何修复该错误
解决这个错误的方法是在第二个geom_line()参数中简单地输入数据,这样R就知道我们试图绘制的是哪个数据框:
library(ggplot2)
#create line chart
ggplot(df, aes(x=hour, y=sales, group=date)) +
geom_line(color='blue') +
geom_line(data=df_new, aes(x=hour, y=sales, group=date), color='red')
注意,这次我们能够成功地创建折线图,没有任何错误。
其他资源
下面的教程解释了如何解决R中的其他常见错误:
如何在R中修复:as.Date.numeric(x)中的错误:必须提供'origin'
如何修复: stripchart.default(x1, ...)中的错误:无效的绘图方法
如何修复: eval(predvars, data, env)中的错误:没有找到对象'x'