希望用 facet_wrap/facet_grid 解决 space = "free" 未解决的问题

Looking to solve problem with facet_wrap/facet_grid that isn't resolved with space = "free"

我正在制作一个具有多个不同方面的水平条形图(y 轴是分类变量,x 轴是百分比)。我 运行 遇到的问题是,如果我使用 facet_wrap(),每个方面的条形宽度都不同(如果我添加 space="free",则格式很奇怪)。我了解到这个问题可以用 facet_grid() 解决,但后来我遇到了每个方面下没有编号的 x 轴的问题。

见下文:

library(tidyverse)

df <- structure(list(Race = c("Asian", "Black"), 
    Symptom1 = c(60L, 40L),
    Symptom2 = c(50L, 20L),
    Symptom3 = c(20L, 50L),
    Symptom4 = c(70L, 50L),
    Symptom5 = c(90L, 85L),
    Symptom6 = c(100L, 30L),
    Symptom7 = c(10L, 30L),
    Symptom8 = c(30L, 20L),
    Symptom9 = c(40L, 80L),
    Symptom10 = c(60L, 40L)), 
    row.names = c(NA, -2L), class = "data.frame")

 b <- df %>% pivot_longer(!Race, names_to = "Symptom", values_to ="Percentage")
 b$Symptom <- fct_rev(factor(b$Symptom, levels = unique(b$Symptom)))

b$Group <- "Benign"
b[c(3:5,13:15),]$Group <- "Warning"
b[c(6:10,16:20),]$Group <- "Fatal"

这提供了一个具有相同条宽但仅在最底部显示 x 轴的图表(而不是也在良性和致命方面)

ggplot(data=b, aes(x=Percentage, y= Symptom, fill = Race)) +
    geom_bar(stat="identity", position=position_dodge()) +
    facet_grid(Group~., scales = "free", space = "free")

这提供了一个图表,每个小平面下都有一个带编号的 x 轴,但条形宽度不均匀

ggplot(data=b, aes(x=Percentage, y= Symptom, fill = Race)) +
    geom_bar(stat="identity", position=position_dodge()) +
    facet_wrap(~Group, scales = "free")

这会提供均匀的条形宽度和带编号的 x 轴,但也会在每个面中创建空的“space”。

ggplot(data=b, aes(x=Percentage, y= Symptom, fill = Race)) +
    geom_bar(stat="identity", position=position_dodge()) +
    facet_wrap(~Group)

有解决办法吗?我想要一个有小平面的图表,每个小平面的条形宽度相等,并且在每个小平面下都有重复编号的 x 轴。

谢谢!

您可以使用 lemon::facet_rep_grid(repeat.tick.labels = T) 而不是 ggplot2::facet_grid() 轻松获得。

library(tidyverse)
library(lemon)

b <- structure(list(Race = c("Asian", "Asian", "Asian", "Asian", "Asian", "Asian", "Asian", "Asian", "Asian", "Asian", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black"), Symptom = structure(c(10L, 9L, 8L, 7L, 6L, 5L, 4L, 3L, 2L, 1L, 10L, 9L,  8L, 7L, 6L, 5L, 4L, 3L, 2L, 1L), .Label = c("Symptom10", "Symptom9", "Symptom8", "Symptom7", "Symptom6", "Symptom5", "Symptom4", "Symptom3", "Symptom2", "Symptom1"), class = "factor"), Percentage = c(60L, 50L, 20L, 70L, 90L, 100L, 10L, 30L, 40L, 60L, 40L, 20L, 50L, 50L, 85L, 30L, 30L, 20L, 80L, 40L), Group = c("Benign", "Benign", "Warning", "Warning", "Warning", "Fatal", "Fatal",  "Fatal", "Fatal", "Fatal", "Benign", "Benign", "Warning", "Warning", "Warning", "Fatal", "Fatal", "Fatal", "Fatal", "Fatal")), row.names = c(NA, -20L), class = c("tbl_df", "tbl", "data.frame"))

ggplot(data=b, aes(x=Percentage, y= Symptom, fill = Race)) +
  geom_bar(stat="identity", position=position_dodge()) +
  facet_rep_grid(Group~., scales = "free", space = "free", repeat.tick.labels = T)

reprex package (v2.0.1)

于 2022 年 1 月 18 日创建