【问题标题】:Draw alternate rectangles in boxplots with facets (R, ggplot2)在带有刻面的箱线图中绘制替代矩形(R,ggplot2)
【发布时间】: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


【解决方案1】:

Things 将根据您提供的 data.frame 中存在的 facet 变量显示适当的 facet。给出一个适当的 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"))

【讨论】:

  • 这对geom_rect 不起作用,是吗? (真诚地问)
  • 同样的原则,使用正确的data.frame和映射,也适用于geom_rect。但是,由于在此示例中您有一个离散的 x 轴,geom_tile 更易于使用。
  • 这就是我得到的geom_rect(data = df_tile, aes(xmin = carb - 0.5, xmax = carb + 0.5, ymin = -Inf, ymax = Inf), fill = 'grey', alpha = 0.5)i.stack.imgur.com/NBiyY.png
  • @M-M 看起来你在 x 轴上仍然有一个数字变量,而这个答案将它转换为一个因子
猜你喜欢
  • 1970-01-01
  • 2019-11-12
  • 2017-10-13
  • 2019-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多