Home > Software engineering >  shaded area between two lines in ggplot
shaded area between two lines in ggplot

Time:10-29

I would like to create a shaded area in color blue between the two dotted lines (-0.5 and 0.5), tried with geom_polygon() but didn't work. How can this be done in the best possible way?

model <- lm(Sepal.Width ~ Petal.Length, data = iris)

ggplot(data.frame(x = seq(model$residuals), y = model$residuals))  
  geom_point(aes(x, y))  
  
  geom_hline(yintercept = 0, linetype = "dashed")  

  geom_hline(yintercept = 0.5, linetype = "dotted")  
  

  geom_hline(yintercept = -0.5, linetype = "dotted")  
  
  
  labs(x = "Index", y = "Residuals", 
       title = paste("Residuals of", format(model$call)))

enter image description here

CodePudding user response:

With annotate:

annotate("rect", xmin = -Inf, xmax = Inf, ymin = -0.5, ymax = 0.5, alpha = .2, fill = "blue")

Output:

ggplot(data.frame(x = seq(model$residuals), y = model$residuals))  
  geom_point(aes(x, y))  
  geom_hline(yintercept = 0, linetype = "dashed")  
  geom_hline(yintercept = c(-0.5, 0.5), linetype = "dotted")  
  annotate("rect", xmin = -Inf, xmax = Inf, ymin = -0.5, ymax = 0.5, alpha = .2, fill = "blue")  
  labs(x = "Index", y = "Residuals", 
       title = paste("Residuals of", format(model$call)))

enter image description here

CodePudding user response:

You can use geom_ribbon

ggplot(data.frame(x = seq(model$residuals), y = model$residuals))  
  geom_point(aes(x, y))  
  geom_ribbon(aes(x, ymin = -0.5, ymax = 0.5), alpha = 0.3, fill = 'steelblue') 
  geom_hline(yintercept = 0, linetype = "dashed")  
  geom_hline(yintercept = 0.5, linetype = "dotted")  
  geom_hline(yintercept = -0.5, linetype = "dotted")  
  labs(x = "Index", y = "Residuals", 
       title = paste("Residuals of", format(model$call)))

enter image description here

  • Related