geom_rect and ggplot2 Error: Aesthetics must be either length 1 or the same as the data (2)

geom_rect and ggplot2 Error: Aesthetics must be either length 1 or the same as the data (2)

我正在尝试执行类似 的操作,但出现错误

Error: Aesthetics must be either length 1 or the same as the data (2): xmin, xmax, ymin, ymax, x, y

“(2)”是什么意思?

涉及哪些'Aesthetics'?我在ggplot中有aes,在geom_rect中有aes,但我不知道如何纠正它们......恐怕我永远不会掌握ggplot ...

days<-rep(Sys.Date(),100)+seq(1,100)
v<-sin(as.numeric(days))
df<-data.frame(days=days,v=v)

shade <- data.frame(x1=c(as.Date('2017-10-15'),as.Date('2017-11-11')), 
                   x2=c(as.Date('2017-10-20'),as.Date('2017-11-13')), 
                   y1=c(-Inf,-Inf), y2=c(Inf,Inf))

library(ggplot2)
plot(ggplot(df,aes(x=days,y=v))
     +geom_line()
     +geom_rect(data=shade, 
               mapping=aes(xmin=x1, xmax=x2, ymin=y1, ymax=y2), color='grey', alpha=0.2)
     +geom_point())

geom_rect 行试图继承顶行 ggplot(df, aes(x = days, y = v)) 的默认美学。

以下方法可行:

ggplot(df, aes(x=days, y=v)) +
  geom_line() +
  geom_rect(data=shade, inherit.aes = F,
            aes(xmin=x1, xmax=x2, ymin=y1, ymax=y2), 
            color = 'grey', alpha=0.2) +
  geom_point()

(我在代码中添加了更多的换行符/空格以便于阅读。另外,没有必要将整个 ggplot 对象包装在 plot() 中。)