Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Colour area above diagonal in the plot as red and below as green in R with ggplot

Tags:

r

ggplot2

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
like image 317
Sven Avatar asked Sep 06 '17 13:09

Sven


1 Answers

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

like image 51
Marco Sandri Avatar answered Nov 17 '22 02:11

Marco Sandri