【发布时间】:2019-07-09 23:48:01
【问题描述】:
我正在使用以下代码。
mtcars2 <- mtcars
library(ggplot2)
mtcars2$carb <- as.factor(mtcars2$carb)
mtcars2$am <- as.factor(mtcars2$am)
sort_table <- data.frame("carb" = c(1,2,3,4,6,8),
"class" = c("class A", "class B", "class A", "class C", "class B", "class A"))
odd_numbers <- seq(1,6,2)
mtcars2 <- merge(mtcars2, sort_table, by = "carb")
ggplot(mtcars2) +
geom_rect(data = mtcars2[odd_numbers, ], xmin = odd_numbers - 0.5, xmax = odd_numbers +
0.5, ymin = -Inf, ymax = Inf, fill = 'grey', alpha = 0.5) +
geom_boxplot(aes(x = carb, y = mpg, fill = am), position = position_dodge(0.9))
现在,我想为每个类添加构面,所以我使用以下代码。
ggplot(mtcars2) +
geom_rect(data = mtcars2[odd_numbers, ], xmin = odd_numbers - 0.5, xmax = odd_numbers +
0.5, ymin = -Inf, ymax = Inf, fill = 'grey', alpha = 0.5) +
geom_boxplot(aes(x = carb, y = mpg, fill = am), position = position_dodge(0.9)) +
facet_grid(cols = vars(class), scales = "free_x", switch = "x", space = "free") +
theme(panel.spacing.x = unit(0, "pt"), strip.background = element_rect(
color="black", size=0.5, linetype="solid"))
不幸的是,阴影现在只应用于第一个面。如何在整个绘图中应用连续阴影,以便在每个方面,以便carb = 6 后面有另一个矩形?谢谢。
【问题讨论】:
-
查看
mtcars[odd_numbers, ]的输出,它只有class A! -
@M-M - 是的,你是对的。您对如何更改代码以更正该问题有什么建议吗?谢谢。
-
@Sylvia 好吧,这不是代码,这是您的数据,没有其他方面的任何内容,因此您看不到任何其他
geom_rect。
标签: r ggplot2 boxplot rectangles