0

I have this data:

structure(list(diff = structure(c(113, 6, 0, -18, -4, -3, -3, 
-6, -6, -250, -7, -27, -8, 0, 0, -4, 0, 2, -1, -3, 0, -5, -5, 
-5, -5, -8, -8, -8, -1, -1, 0, -1, -11, 0, 0, 0, 0, -1, -7, -8, 
-3, -11, -60, -1, 0, 0, 0, 0, -124, -123), class = "difftime", units = "days")), row.names = c(NA, 
50L), class = "data.frame")

which produces this boxplot

ggplot(df) +
  geom_boxplot(
    aes(
      x = diff
    )
  ) +
  theme_light()

enter image description here

I would like to color the left side of the panel (left to the median) in a color. And the right side of the panel in another color.

I just do not know how to get e.g. the minimum x-value of the panel (something around ~2700 maybe) and all the other three values (xmax, ymin, ymax), to get the proper aesthetics in a ggplot call roughly like this:

m = median(df$diff)
ggplot(df) +
  geom_boxplot(
    aes(
      x = diff
    )
  ) +
  geom_rect( # the left side
   aes(
     xmin = <xmin_of_panel>,
     xmax = m,
     ymax = <ymax_of_panel>,
     ymin = <ymin_of_panel>
   ) 
  ) +
  geom_rect( # the right side
   aes(
     xmin = m,
     xmax = <xmax_of_the_panel>,
     ymax = <ymax_of_panel>,
     ymin = <ymin_of_panel>
   ) 
  ) +
  theme_light()

Maybe I can save the ggplot-object as a variable and get the coordinates limits as described here:

How can I extract plot axes' ranges for a ggplot2 object?

But I'm not really sure how to do this properly

Ian Campbell
  • 23,484
  • 14
  • 36
  • 57
Lenn
  • 1,283
  • 7
  • 20

1 Answers1

1

You can just use Inf instead of the actual limits. Clipping will take care fo the rest:

ggplot(df) +
  geom_rect(aes(xmin = -Inf, xmax = median(diff), ymin = -Inf, ymax = Inf,
                fill = "A"), show.legend = FALSE) + 
    geom_rect(aes(xmin = median(diff), xmax = Inf, ymin = -Inf, ymax = Inf,
                fill = "B"), show.legend = FALSE) + 
  scale_fill_manual(values = c("firebrick3","forestgreen")) +
  geom_boxplot(aes(diff)) +
  theme_light()

enter image description here

Ian Campbell
  • 23,484
  • 14
  • 36
  • 57