简体   繁体   中英

Drawing rectangles on boxplot (ggplot2 in R)

Using the mtcars data as an example, I generated a boxplot and would like to add rectangles. Here is my full code.

 library(ggplot2)
 d=data.frame(x1=c(1,3,1,5,4), x2=c(2,4,3,6,6), y1=c(10,10,20,14,30), y2=c(15,20,25,18,35), t=c('a','a','a','b','b'))
 ggplot(mtcars, aes(x = as.factor(mtcars$carb), y = mpg)) + geom_boxplot() + geom_rect(data=d, mapping=aes(xmin=x1, xmax=x2, ymin=y1, ymax=y2, fill=t), color="black", alpha=0.5)

However, this does not work due to an aesthetics issue. I do not understand why, because each of the two above parts work separately, so:

 #part 1 (works)
 ggplot(mtcars, aes(x = as.factor(mtcars$carb), y = mpg)) + geom_boxplot()

 #part 2 (works)
 ggplot() + geom_rect(data=d, mapping=aes(xmin=x1, xmax=x2, ymin=y1, ymax=y2, fill=t), color="black", alpha=0.5)

I would appreciate any suggestions. Thank you.

Here's an example of how this could work. The important thing is that ggplot expects all the layers' x-axes to be either continuous or discrete, not a mix. (And same for the y-axes.)

In your example, the boxplot x axis is on a discrete (aka ordinal) scale, like if you had one location for "orange" and another for "pineapple." But the rect is defined on a continuous scale, like 1, 2, 3. ggplot typically requires you to pick one kind or the other; if necessary you can coerce one into the other but you'd need to define how. ie Is "2" on the left or on the right of "pineapple"?

So for this to work, you can't feed the geom_plot layer a factor for the x-axis, at least without converting it to numeric somehow. Here I just leave it as the original number it started as, and add a group = carb term so that we get a boxplot for every carb value, not all of them in total in one group.

ggplot(mtcars) + 
  geom_boxplot(aes(x = carb, y = mpg, group = carb)) +
  geom_rect(data=d, aes(xmin=x1, xmax=x2, ymin=y1, ymax=y2, fill=t), color="black", alpha=0.5)

在此处输入图片说明

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