R中ggplot的背景带

Background bands with ggplot in R

我正在尝试为不同的组创建箱线图。我想在 3 个水平带中为背景着色。一个中心的,所有观察值都接近总体平均值

平均值(体重)-0.5 < x < 平均值(体重)+0.5

另外2个波段是下波段和上波段。

这些是我的情节

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

使用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)

哪个给你这个数字:

希望您能更改背景颜色:)