Filling area above square in grey ggplot2

Viewed 94

I am trying to fill the area above and right to the square in light grey. The background inside the square should be white and the point inside there still visible. The background above and to the right of the square should be light grey and the points there visible as well.

The "fill=blue" and "alpha=0" was just a bad workaround to obtain a white area there, but the blue is not really needed there.

enter image description here

Here is a short reproducible example

data_Z_pairs <- data.frame(Z = c(0.20, 0.1, 0.03), Z_tild = c(0.15, 0.03, 0.02))

p1 <- ggplot(data_Z_pairs, aes(Z, Z_tild))
p2 <- p1 + geom_point() + 
  theme_bw()  +
  theme(panel.grid = element_blank()) +
  geom_abline(slope=1, intercept = 0, linetype = "dashed") +  
  geom_rect(mapping=aes(xmin=0, xmax=t0, ymin=0, ymax=t0, fill ="blue"), 
            alpha=0, color = "black") #


p2

I have tried it somehow with "geom_polygon" so far, but could not achieve my desired result

1 Answers

Try:

data_Z_pairs <- data.frame(Z = c(0.20, 0.1, 0.03), Z_tild = c(0.15, 0.03, 0.02))


library(ggplot2)

t0 <- 0.05


ggplot(data_Z_pairs, aes(Z, Z_tild))+
  geom_point() + 
  geom_abline(slope=1, intercept = 0, linetype = "dashed") +  
  geom_rect(aes(xmin=0, xmax=t0, ymin=0, ymax=t0), alpha = 0, colour = "black")+
  geom_rect(aes(xmin = t0, xmax = Inf,  ymin = -Inf, ymax = Inf), fill = "gray80", alpha = 0.2)+
  geom_rect(aes(xmin = -Inf, xmax = t0,  ymin = t0, ymax = Inf), fill = "gray80", alpha = 0.2)+
  geom_rect(aes(xmin = -Inf, xmax = 0,  ymin = -Inf, ymax = t0), fill = "gray80", alpha = 0.2)+
  geom_rect(aes(xmin = -0, xmax = t0,  ymin = -Inf, ymax = 0), fill = "gray80", alpha = 0.2)+
  theme_bw()  +
  theme(panel.grid = element_blank())

If you literally want only the areas above and to the right of the box shaded then adjust the light grey geom_rect layers as follows:



ggplot(data_Z_pairs, aes(Z, Z_tild))+
  geom_point() + 
  geom_abline(slope=1, intercept = 0, linetype = "dashed") +  
  geom_rect(aes(xmin=0, xmax=t0, ymin=0, ymax=t0), alpha = 0, colour = "black")+
  geom_rect(aes(xmin = t0, xmax = Inf,  ymin = 0, ymax = Inf), fill = "gray80", alpha = 0.2)+
  geom_rect(aes(xmin = 0, xmax = t0,  ymin = t0, ymax = Inf), fill = "gray80", alpha = 0.2)+
  theme_bw()  +
  theme(panel.grid = element_blank())

Or using geom_polygon the same result is achieved with providing a separate dataframe with corner coordinates:

pos <- data.frame(x = c(0, 0, Inf, Inf, t0, t0, 0),
                  y = c(t0, Inf, Inf, 0, 0, t0, t0))

ggplot(data_Z_pairs, aes(Z, Z_tild))+
  geom_point() + 
  geom_abline(slope=1, intercept = 0, linetype = "dashed") +  
  geom_rect(aes(xmin=0, xmax=t0, ymin=0, ymax=t0), alpha = 0, colour = "black")+
  geom_polygon(data = pos, aes(x, y), fill = "gray80", alpha = 0.2)+
  theme_bw()  +
  theme(panel.grid = element_blank())

Created on 2021-04-20 by the reprex package (v2.0.0)

Related