r - geom_ribbon不起作用-eval(expr,envir,enclos): object 'variable' not found中的错误

标签 r plot ggplot2 ribbon

我尝试将geom_ribbon对象添加到我的ggplot2图中。在我的数据框中,我有NA值(我想)可能会引起问题。这是我拥有的数据帧的可复制示例:

base <- c(1:10, rep(NA, 10))
output1 <- c(rep(NA, 9), 10 - 0:10)
output2 <- c(rep(NA, 9), 10 + 0:10)
xaxis <- 1:20

df <- data.frame(xaxis, base, output1, output2)
df

     xaxis base output1 output2
  1      1    1      NA      NA
  2      2    2      NA      NA
  3      3    3      NA      NA
  4      4    4      NA      NA
  5      5    5      NA      NA
  6      6    6      NA      NA
  7      7    7      NA      NA
  8      8    8      NA      NA
  9      9    9      NA      NA
  10    10   10      10      10
  11    11   NA       9      11
  12    12   NA       8      12
  13    13   NA       7      13
  14    14   NA       6      14
  15    15   NA       5      15
  16    16   NA       4      16
  17    17   NA       3      17
  18    18   NA       2      18
  19    19   NA       1      19
  20    20   NA       0      20

我试图用ggplot2绘制geom_ribbon对象:
  dfm <- melt(df, id=1)
  ggplot(dfm, aes(x = xaxis, y = value, colour = variable)) + 
    geom_line(aes(group=variable)) + 
    geom_ribbon(data=df, aes(group = 1, ymin=output1, ymax=output2))

最终,我遇到了错误,无法处理:
Error in eval(expr, envir, enclos) : object 'variable' not found

预先感谢您的任何建议。

最佳答案

之所以出现此错误,是因为variable用于aes()函数的ggplot()中的颜色。当您将geom_ribbon()与新数据框添加在一起时,geom_ribbon()会尝试在新数据框中查找variable以将其用于颜色。要忽略此变量,请在inherit.aes=FALSE内添加geom_ribbon()-因此,您要告知所有参数都应独立使用-这样,您应该在x=xaxis中再次设置geom_ribbon()

ggplot(dfm, aes(x = xaxis, y = value, colour = variable)) + 
  geom_line(aes(group=variable)) + 
  geom_ribbon(data=df, aes(group = 1, x = xaxis,ymin=output1, ymax=output2),
                       inherit.aes=FALSE)

关于r - geom_ribbon不起作用-eval(expr,envir,enclos): object 'variable' not found中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19891637/

相关文章:

绘制海龟与能量的关系图

R ggplot2 用 2 个 hlines 和正确的图例绘制单个数据

r - 打印r向量以将粘贴复制到其他代码中。

r - 在 scatter3d 中显示点标签

r - 从头开始创建geom/stat

r - 在 R 中绘制图形并将其循环导出到 Excel

r - 线性回归线无法在 r 中的时间序列图上显示

r - ggplotly 没有适用于 'plotly_build' 的方法应用于类 "NULL"if 语句的对象

r - R 中的灰度堆积面积图

R线性回归问题: lm. fit(x, y, offset = offset, Single.ok = Single.ok, ...)