简体   繁体   中英

Add horizontal rectangle to categorical boxplot in ggplot2

I want to make a boxplot with a horizontal rectangle behind the plots (or above with opacity). I am not sure how to do this with categorical x-axis values and force it to extend the entire width of the plot area. This answer was helpful, but I'm not sure how to extend the rectangle to the edges of the plot area.

Let's say we want to make a rectangle across the diamonds cuts between $3000 and $5000. I have attempted the code below, but it doesn't extend to the edge of the plot.

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)

Output

带矩形的箱线图

To get the rectangle to the panel edges you can set the limits as +/-Inf.

Also for a single rectangle like this (and not mapping any aesthetics) it may be worth just using annotate :

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

but for completeness, you can still use a geom_rect call

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

You can move the rectangle behind the boxplots by changing the order of the geoms.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM