5

I would like to colour the area above the diagonal as red and below as green with ggplot. I have read through geom_ribbon, but as far as I have understood I can only specify the y-value. Can somebody please support? Thank you very much.

# Test data
df <- data.frame(
  x = sample(1:100, 100, replace=FALSE),
  y = sample(1:100, 100, replace=FALSE))

library(ggplot2)
g <- ggplot(data=df, aes(x=x, y=y))
g + 
   geom_point() +
   geom_abline(intercept = 0, slope = 1) 
   # + geom_ribbon(aes(ymin=2 , ymax=50), fill="red", alpha=0.2) not working
Sven
  • 443
  • 2
  • 10
  • Answers to [this question](https://stackoverflow.com/questions/6801571/ggplot2-shade-area-above-line) may be useful. – Z.Lin Sep 06 '17 at 13:43

1 Answers1

5

geom_polygon can be used for coloring the upper and lower triangular areas.

# Test data
df <- data.frame(
  x = sample(1:100, 100, replace=FALSE),
  y = sample(1:100, 100, replace=FALSE))

# Coordinates of the upper and lower areas
trsup <- data.frame(x=c(0,0,100),y=c(0,100,100))
trinf <- data.frame(x=c(0,100,100),y=c(0,0,100))

library(ggplot2)
# Use geom_polygon for coloring the two areas
g <- ggplot(data=df, aes(x=x, y=y))
g + geom_point() +
    geom_abline(intercept = 0, slope = 1) +
    geom_polygon(aes(x=x, y=y), data=trsup, fill="#FF000066") +
    geom_polygon(aes(x=x, y=y), data=trinf, fill="#00FF0066")

enter image description here

Marco Sandri
  • 23,289
  • 7
  • 54
  • 58