Background stripes with ggplot in R

I am trying to create field charts for different groups. I would like to color the background with 3 horizontal stripes. Central, where all observations are close to the mean

average (weight) -0.5 <x <mean (weight) +0.5

The other 2 stripes are bottom and top.

Here is my plot

library(ggplot2)
bp <- ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot()
bp

      

+3


source to share


1 answer


Use geom_rect

:

bp <- ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) +
    geom_rect(ymin = -Inf, ymax = lwWt, 
              xmin = -Inf, xmax = Inf, fill = 'blue') +
    geom_rect(ymin = lwWt, ymax = upWt, 
              xmin = -Inf, xmax = Inf, fill = 'pink') + 
    geom_rect(ymin = upWt, ymax = Inf, 
          xmin = -Inf, xmax = Inf, fill = 'skyblue') +
    geom_boxplot() 
print(bp)
ggsave("example.jpg", bp)

      



What this drawing gives you: enter image description here

We hope you change the background colors :)

+4


source







All Articles