Home > Software engineering >  ggplot2 geom_ribbon with a different dataset is not working
ggplot2 geom_ribbon with a different dataset is not working

Time:04-06

I am creating a ggplot with the main data and I want to add a geom_ribbon from a different dataset, I thought this would be similar to adding a geom_line for instance but I am hitting a dead end...

Here is a reproducible example using data from the geom_ribbon help:

huron <- data.frame(year = 1875:1972, level = as.vector(LakeHuron))
huron2 <- data.frame(year = 1875:1972, min_level = as.vector(LakeHuron)-10,max_level = as.vector(LakeHuron) 10)
# This works fine
ggplot(huron,aes(x=year,y=level)) 
  geom_line() 
  geom_line(data=huron2,aes(x=year,y=min_level),colour="lightblue")

# But this throws an error (Error in FUN(X[[i]], ...) : object 'level' not found)
ggplot(huron,aes(x=year,y=level)) 
  geom_line() 
  geom_ribbon(data=huron2,aes(x=year,ymin=min_level,ymax=max_level),colour="lightblue",alpha=0.5) 

Am I missing something obvious here?

CodePudding user response:

You can adjust your code to get the desired output:

ggplot() 
  geom_line(data = huron, aes(x=year,y=level)) 
  geom_ribbon(data = huron2, aes(x = year, ymin = min_level, ymax = max_level), fill = "lightblue", alpha = 0.5) 

enter image description here

Note you originally had colour = "lightblue" which will only change the lines, so (assuming you want the range to be colored, not grey) I changed it to fill = "lightblue"

  • Related