【问题标题】:geom_rect and ggplot2 Error: Aesthetics must be either length 1 or the same as the data (2)geom_rect 和 ggplot2 错误:美学必须是长度 1 或与数据相同 (2)
【发布时间】:2018-02-24 11:43:13
【问题描述】:

我正在尝试执行https://stackoverflow.com/a/29649406/15485 之类的操作,但出现错误

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

“(2)”是什么意思?

涉及哪些“美学”?我在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())

【问题讨论】:

  • 顺便说一句,(2) 表示data 的长度当前为 2。也就是说,美学只允许为当前定义的 1 或 2。 @Z.Lin 说明了原因。

标签: r ggplot2 aesthetics


【解决方案1】:

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() 中。)

【讨论】:

  • 非常感谢!实际上在stackoverflow.com/a/29649406/15485 geom_line 有自己的Aestheticsggplot 没有。
  • 在 RStudio 中我需要用plot() 包裹,否则不会生成图表...
  • @AlessandroJacopson 那是因为您的 + 运算符位于下一行的开头,而不是上一行的结尾。将它们向上移动(根据我的示例),您将看到图表。
  • 在我的 RStudio 版本 1.0.153(在 Windows 上)中,您的代码不会创建情节......无论如何我可以忍受 :-)
  • 嗯,您是在采购脚本/将其包装在一个函数中吗? This 可能是相关的。
猜你喜欢
  • 2016-08-06
  • 1970-01-01
  • 2016-10-13
  • 1970-01-01
  • 2017-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多