【发布时间】:2019-11-12 16:13:54
【问题描述】:
我想在箱线图中绘制交替的阴影/矩形,类似于本文中的第二张图片: Adding shading alternate areas for categorical variable in a bar plot in ggplot2
以下是我的代码,以 mtcars 为例。我将 carb 和 cyl 转换为 factor 以更好地匹配我的真实数据和代码
library(ggplot2)
odd_numbers <- seq(1,33,2)
mtcars$carb <- as.factor(mtcars$carb)
mtcars$cyl <- as.factor(mtcars$cyl)
ggplot(mtcars) +
geom_boxplot(aes(x = carb, y = mpg, fill = cyl), position = position_dodge(0.9)) +
geom_rect(data = mtcars, aes(x = carb, y = mpg),
xmin= as.numeric(mtcars$carb[odd_numbers]) - 0.5,
xmax = as.numeric(mtcars$carb[odd_numbers]) + 0.5,
ymin = -Inf,
ymax = Inf, fill='grey', alpha=0.5)
我以为x轴为数值的问题在代码中已经解决了,但还是有问题:
警告:忽略未知的美学:x,y
错误:美学长度必须为1或与数据相同(32):xmin,xmax
请问有人给点建议吗?谢谢。
编辑
在 cmets 之后,我编辑了代码,如下所示:
- 删除了[odd_numbers]
- 交换geom_boxplot和geom_rect的顺序
代码:
library(ggplot2)
odd_numbers <- seq(1,33,2)
mtcars$carb <- as.factor(mtcars$carb)
mtcars$cyl <- as.factor(mtcars$cyl)
ggplot(mtcars) +
geom_rect(data = mtcars, aes(x = carb, y = mpg),
xmin= as.numeric(mtcars$carb) - 0.5,
xmax = as.numeric(mtcars$carb) + 0.5,
ymin = -Inf,
ymax = Inf, fill='grey', alpha=0.5) +
geom_boxplot(aes(x = carb, y = mpg, fill = cyl), position = position_dodge(0.9))
这会导致以下结果,所以还没有。谢谢。
想要的结果与此类似:
【问题讨论】:
-
您将 xmin/xmax 限制为仅奇数(长度 17),但您的数据长度为 32。只需删除 [odd_numbers] 位?
-
@RAB 不,使用
geom_rect(data = mtcars[odd_numbers, ]。并交换geom_rect和geom_boxplot以使框覆盖灰色条。 -
@RAB 和 Rui Barradas:感谢您的建议。请在上面进行编辑。
标签: r ggplot2 rectangles