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

Shading region between vertical and diagonal lines in ggplot

I am trying to use ggplot to shade the region between the vertical line and the diagonal line as shown below. Is there a way to do this?

df <- data.frame(x=c(1,-1), y=c(1,-1))

ggplot(df, aes(x, y)) +
  geom_point() +
  geom_abline(slope=-1) +
  geom_vline(xintercept = 0)

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 :

It is a bit tricky, but if you know the coordinates of the area (Inf), you can use them to fill the shades using geom_polygon like this:

library(ggplot2)
df <- data.frame(x=c(1,-1), y=c(1,-1))
upper_area <- data.frame(x=c(-Inf,0,0),y=c(Inf,Inf,0))
down_area <- data.frame(x=c(0,0,Inf),y=c(0,-Inf,-Inf))

ggplot(df, aes(x, y)) +
  geom_point() +
  geom_abline(slope=-1) +
  geom_vline(xintercept = 0) +
  geom_polygon(aes(x=x, y=y), data=upper_area, fill="red") +
  geom_polygon(aes(x=x, y=y), data=down_area, fill="blue")

Created on 2022-07-15 by the reprex package (v2.0.1)

old answer

It is a bit tricky, but if you know the coordinates of the area, you can use them to fill the shades using geom_polygon like this:

library(ggplot2)
df <- data.frame(x=c(1,-1), y=c(1,-1))
upper_area <- data.frame(x=c(-1,0,0),y=c(1,1,0))
down_area <- data.frame(x=c(0,0,1),y=c(0,-1,-1))

ggplot(df, aes(x, y)) +
  geom_point() +
  geom_abline(slope=-1) +
  geom_vline(xintercept = 0) +
  geom_polygon(aes(x=x, y=y), data=upper_area, fill="red") +
  geom_polygon(aes(x=x, y=y), data=down_area, fill="blue")

Created on 2022-07-15 by the reprex package (v2.0.1)

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