在带刻面的箱线图中绘制交替矩形(R,ggplot2)

Draw alternate rectangles in boxplots with facets (R, ggplot2)

我正在使用以下代码。

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

这很好地生成了这个带有交替阴影的箱线图。

现在,我想为每个 class 添加分面,所以我使用以下代码。

 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 后面有另一个矩形?谢谢。

根据您提供的 data.frame 中存在的方面变量,事物将显示适当的方面。给一个合适的data.frame,有合适的映射,例如:

df_tile <- data.frame(carb = c(1, 8, 6), class = c('class A', 'class A', 'class B'))

ggplot(mtcars) + 
    geom_tile(aes(x = factor(carb), y = 1, height = Inf, width = 1), data = df_tile, alpha = 0.3) + 
    geom_boxplot(aes(x = carb, y = mpg, fill = am), position = position_dodge(0.9)) + 
    facet_grid(cols = vars(class), scales = "free_x", space = "free") + 
    theme(panel.spacing.x = unit(0, "pt"), strip.background = element_rect(
        color="black", size=0.5, linetype="solid"))