Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

shaded area between two lines in ggplot

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading