在带有刻面(R,ggplot2)的箱图中绘制备用矩形

时间:2019-07-09 23:48:01

标签: r ggplot2 boxplot rectangles

我正在使用以下代码。

index.php

这很好地产生了带有交替阴影的箱形图。 enter image description here

现在,我想为每个类添加构面,因此我使用以下代码。

 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))

这将产生以下箱线图。 enter image description here

不幸的是,阴影现在仅应用于第一个构面。如何在整个图上对每个面应用连续的阴影,以便在 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")) 之后有另一个矩形?谢谢。

1 个答案:

答案 0 :(得分:3)

事物将根据您提供的data.frame中存在的facet变量显示适当的facet。提供适当的data.frame,并进行适当的映射,例如:

LateUpdate

enter image description here