'Looking to solve problem with facet_wrap/facet_grid that isn't resolved with space = "free"
I am making a horizontal bar graph with multiple different facets (y axis is categorical variable, x-axis is percentages). I am running into the problem that if I use facet_wrap() the bar widths are different in each of the facets (with weird formatting if I add space="free"). I learned this problem can be solved with facet_grid() but then I have the problem of not having numbered x-axises under each facet.
See below:
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"
This provides a graph that has same bar widths but only displays the x axis at the very bottom (as opposed to also under the benign and fatal facets as well)
ggplot(data=b, aes(x=Percentage, y= Symptom, fill = Race)) +
geom_bar(stat="identity", position=position_dodge()) +
facet_grid(Group~., scales = "free", space = "free")
This provides a graph with a numbered x-axis under each facet but uneven bar widths
ggplot(data=b, aes(x=Percentage, y= Symptom, fill = Race)) +
geom_bar(stat="identity", position=position_dodge()) +
facet_wrap(~Group, scales = "free")
This provides even bar widths and a numbered x-axis but also then creates empty "space" in each facet.
ggplot(data=b, aes(x=Percentage, y= Symptom, fill = Race)) +
geom_bar(stat="identity", position=position_dodge()) +
facet_wrap(~Group)
Is there a solution to this? I would love a graph that has facets, has equal bar widths in each facet, and has repeated numbered x-axises under each of the facets.
Thanks!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
