I have the following plot:
Sample code:
dat = data.frame(grp = rep(c("Group1", "Group2"), 24),
label = rep(c(rep("Yes",2), rep("Rather yes",2), rep("Rather no",2), rep("No",2)), 6),
pct = rep(c(25,25,25,25), 12),
grp2 = c(rep("Total", 8),rep("Age", 24),rep("Gender", 16)),
label2 = c(rep("",8), rep("18-29", 8),rep("30-64", 8),rep("65-80", 8),rep("Male", 8),rep("Female", 8)))
dat$grp2 <- factor(dat$grp2, levels = c("Total", "Gender", "Age"))
# Design for facet_manual (ggh4x-Package)
design <- matrix(1:6,3)
heights <- c(8,16,24)
# Plot
plot <- ggplot2::ggplot(data = dat, ggplot2::aes(x = pct, y = label2, fill = label)) +
ggplot2::geom_bar(stat = 'identity', position = 'stack', width = 0.8, color = 'white') +
ggh4x::facet_manual(grp~grp2, design = design, heights = heights, scales = "free_y", strip.position = "top");plot
I would like very much that Group1 or Group2 is written only once, at the top of the plot. One possibility I found is to select what is shown using labeller. But I do not understand the structure of the underlying labeller object (in the example only the inner label is shown, not as I want 1x outer label at the top and all inner labels).
plot <- ggplot2::ggplot(data = dat, ggplot2::aes(x = pct, y = label2, fill = label)) +
ggplot2::geom_bar(stat = 'identity', position = 'stack', width = 0.8, color = 'white') +
ggh4x::facet_manual(grp~grp2, design = design, heights = heights, scales = "free_y", strip.position = "top",
labeller = function(df) {list(as.character(df[,2]))});plot
Does anyone have a solution? Of course it would also be possible to create two plots and then attach them next to each other. But I would be interested in a solution that generates a plot directly with facets.
I already tried using different labeller functions as well as using facet_nested_wrap as an Alternative.