Geom_ribbon not working - Error in eval (expr, envir, enc): object 'variable' not found

I am trying to add a geom_ribbon object to my ggplot2 . In my data frame, I have NA values ​​that (I think) might cause the problem. This is a reproducible example of a data frame that I have:

 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 

And my attempt to build a ggplot2 object using 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)) 

And in the end, I got an error that I can not handle :

 Error in eval(expr, envir, enclos) : object 'variable' not found 

Thanks in advance for any suggestions.

+6
source share
2 answers

You got this error because variable used for color in aes() the ggplot() function. When you add geom_ribbon() with a new data frame, geom_ribbon() tries to find the variable in the new data frame to use it for colors. To ignore this variable, add inherit.aes=FALSE inside geom_ribbon() - so you say that all parameters must be taken independently - this way you must set x=xaxis to geom_ribbon() again.

 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) 
+13
source

The definition for color = variable carried over from the source ggplot layer. Turn it over in a geom_ribbon call to make it work: geom_ribbon(data = df, aes(group = 1, ymin=output1, ymax=output2, color=I('red')) .

+2
source

Source: https://habr.com/ru/post/957774/


All Articles