4

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
    The issue is related to the use of the `Inf`s. See https://stackoverflow.com/questions/63951513/fill-background-intervals-in-ggplotly-line-graph for a possible solution. – stefan Apr 14 '21 at 09:01

1 Answers1

1

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

TarJae
  • 72,363
  • 6
  • 19
  • 66
  • Thank you for your answer. Your plot is quite similar to what I already have. But as my code, it is not working with ggplotly, too. I've added another picture to my question. Maybe my problem will then get more clear. I'd like the panel background above the black line to be red and under the black line to be green. I've found a similar problem here: [link](https://stackoverflow.com/questions/20980622/change-background-color-on-just-one-region-of-the-graph), but I don't want a rectangle region to be in a different colour. Instead, I want the triangles above and under the line to be different. –  Apr 14 '21 at 15:05
  • It's also very important that the code works with the function ggplotly, too, as I'm building a shiny application in R. –  Apr 14 '21 at 15:10