如何处理 ggplot2中的“类的数据 uneval”错误?

当试图将一条新线与现有的 ggplot重叠时,我得到了以下错误:

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

我的代码的第一部分工作得很好。下面是一张来自美国中西部电力市场的“最近”每小时风力发电数据的图片。

Recent Hourly Wind Data

现在我要用红色覆盖过去两天的观察结果。这应该很容易,但我不明白为什么我会得到一个错误。

如果您能提供帮助,我将不胜感激。

下面是一个可重复的例子:

# Read in Wind data
fname <- "https://www.midwestiso.org/Library/Repository/Market%20Reports/20130510_hwd_HIST.csv"
df <- read.csv(fname, header=TRUE, sep="," , skip=7)
df <- df[1:(length(df$MKTHOUR)-5),]


# format variables
df$MWh <- as.numeric(df$MWh)
df$Datetime <- strptime(df$MKTHOUR, "%m/%d/%y %I:%M %p")


# Create some variables
df$Date  <- as.Date(df$Datetime)
df$HrEnd <- df$Datetime$hour+1


# Subset recent and last data
last.obs  <- range(df$Date)[2]
df.recent <- subset(df, Date %in% seq(last.obs-30, last.obs-2, by=1))
df.last   <- subset(df, Date %in% seq(last.obs-2,  last.obs,   by=1))


# plot recent in Grey
p <- ggplot(df.recent, aes(HrEnd, MWh, group=factor(Date))) +
geom_line(color="grey") +
scale_y_continuous(labels = comma) +
scale_x_continuous(breaks = seq(1,24,1)) +
labs(y="MWh") +
labs(x="Hour Ending") +
labs(title="Hourly Wind Generation")
p


# plot last two days in Red
p <- p + geom_line(df.last, aes(HrEnd, MWh, group=factor(Date)), color="red")
p
132088 次浏览

when you add a new data set to a geom you need to use the data= argument. Or put the arguments in the proper order mapping=..., data=.... Take a look at the arguments for ?geom_line.

Thus:

p + geom_line(data=df.last, aes(HrEnd, MWh, group=factor(Date)), color="red")

Or:

p + geom_line(aes(HrEnd, MWh, group=factor(Date)), df.last, color="red")

Another cause is accidentally putting the data=... inside the aes(...) instead of outside:

RIGHT:
ggplot(data=df[df$var7=='9-06',], aes(x=lifetime,y=rep_rate,group=mdcp,color=mdcp) ...)


WRONG:
ggplot(aes(data=df[df$var7=='9-06',],x=lifetime,y=rep_rate,group=mdcp,color=mdcp) ...)

In particular this can happen when you prototype your plot command with qplot(), which doesn't use an explicit aes(), then edit/copy-and-paste it into a ggplot()

qplot(data=..., x=...,y=..., ...)


ggplot(data=..., aes(x=...,y=...,...))

It's a pity ggplot's error message isn't Missing 'data' argument! instead of this cryptic nonsense, because that's what this message often means.

This could also occur if you refer to a variable in the data.frame that doesn't exist. For example, recently I forgot to tell ddply to summarize by one of my variables that I used in geom_line to specify line color. Then, ggplot didn't know where to find the variable I hadn't created in the summary table, and I got this error.