geom_rect 和 ggplot2 错误:美学必须是长度 1 或与数据相同 (2)

Ale*_*son 2 r ggplot2 aesthetics

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

错误:Aesthetics 必须为长度 1 或与数据 (2) 相同:xmin, xmax, ymin, ymax, x, y

“(2)”是什么意思?

涉及哪些“美学”?我已经aesggplotaesgeom_rect,但我不知道如何解决这些问题的想法,我很害怕我永远不会掌握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())
Run Code Online (Sandbox Code Playgroud)

Z.L*_*Lin 5

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()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

(为了便于阅读,我在代码中添加了更多换行符/空格。此外,无需将整个 ggplot 对象包装在plot().)