R - Change background colour with ggplotly

Viewed 80

I'd like to change the background of my R plot as shown in the picture below (see result plot). The plot has a bisector and I'd like the background above the bisector to be red and under the bisector to be green.

That's what I already tried, but unfortunately it doesn't work with ggplotly.

# The code

data <- data.frame(y=c(Inf,Inf,0), x=c(0,Inf,0), y_new=c(0,0,Inf),x_new=c(0,Inf,Inf))

test <- ggplot(data) + 
  geom_polygon(aes(x=x, y=y), colour="red",fill="red") + 
  geom_polygon(aes(x=x_new, y=y_new), colour="green",fill="green") +
  geom_abline(slope = 1, intercept= 0)
ggplotly(test)

Thank you for every hint that might help me!

result plot

Current status of my plot

1 Answers

Are you looking for this kind of solution?

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

df_poly_lower <- data.frame(
  x=c(Inf, Inf, -Inf),
  y=c(Inf, -Inf, -Inf)
)

ggplot(df, aes(x, y)) + 
  geom_blank() + 
  geom_abline(slope=1, intercept=0) + 
  geom_polygon(data=df_poly_upper, aes(x, y), fill="red") + 
  geom_polygon(data=df_poly_lower, aes(x, y), fill="green") 

enter image description here

Related