简体   繁体   English

在boxplot(R中的ggplot2)上绘制矩形

[英]Drawing rectangles on boxplot (ggplot2 in R)

Using the mtcars data as an example, I generated a boxplot and would like to add rectangles. 以mtcars数据为例,我生成了一个箱线图,并希望添加矩形。 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. 重要的是ggplot期望所有图层的x轴是连续或离散的,而不是混合的。 (And same for the y-axes.) (对于y轴也是如此。)

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." 在您的示例中,箱线图x轴是离散的(也称为有序)标度,就像您有一个位置表示“橙色”而另一个位置表示“菠萝”一样。 But the rect is defined on a continuous scale, like 1, 2, 3. ggplot typically requires you to pick one kind or the other; 但是rect是按连续的比例定义的,例如1、2、3。ggplot通常要求您选择一种或另一种。 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"? 即“菠萝”的左边还是右边是“ 2”?

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. 因此,要使其正常工作,就不geom_plot层作为x轴的一个因子,至少不能以某种方式将其转换为数值。 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. 在这里,我只是将其保留为开始时的原始编号,然后添加一个group = carb项,以便我们获得每个carb值的箱线图,而不是一组中的所有总和。

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)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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