首页 > 解决方案 > 在ggplot2中将水平矩形添加到分类箱线图

问题描述

我想制作一个带有水平矩形的箱线图(或在不透明度上方)。我不确定如何使用分类 x 轴值执行此操作并强制它扩展绘图区域的整个宽度。这个答案很有帮助,但我不确定如何将矩形扩展到绘图区域的边缘。

假设我们想在diamonds3000 美元到 5000 美元之间的切口上画一个矩形。我尝试了下面的代码,但它没有延伸到情节的边缘。

rectangle <- data.frame(x = c("Fair","Good","Very good", "Premium", "Ideal"), 
                    lower = rep(3000, 5),
                    upper = rep(5000, 5))
ggplot() +
  geom_boxplot(data=diamonds, aes(x=cut, y=price)) +
  geom_rect(data=rectangle, aes(xmin="Fair", xmax="Ideal", 
                                ymin=lower, ymax=upper), alpha=0.1)

输出

带矩形的箱线图

标签: rggplot2

解决方案


要使矩形到达面板边缘,您可以将限制设置为 +/-Inf。

同样对于像这样的单个矩形(而不是映射任何美学),它可能值得使用annotate

annotate("rect", xmin=-Inf, xmax=Inf, ymin=3000, ymax=5000, alpha=0.4)

但为了完整起见,您仍然可以使用geom_rect通话

geom_rect(aes(xmin=-Inf, xmax=Inf, ymin=3000, ymax=5000), alpha=0.4)

您可以通过更改几何图形的顺序来移动箱线图后面的矩形。

ggplot(diamonds, aes(x=cut, y=price)) +
    geom_blank() +
    annotate("rect", xmin=-Inf, xmax=Inf, ymin=3000, ymax=5000) +
    geom_boxplot()

推荐阅读