I have the following graph in ggplot and i’ve used facet_grid (the image only shows facet b) but I can’t get scales=free to work in facet_grid so that the attribute levels with less than 6 bars shrinks to take up less space accordingly.
I have indicated where I have tried to do this with ####’s
ggplot code:
Plot5 <-
ggplot(data = filtered_df,
mapping = aes(x = rel_change,
fill = scenario,
y = factor(attribute_level, levels = c(
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H")))) +
geom_col(position = position_dodge2(width = 1, preserve = "single")) +
theme_article() +
scale_fill_manual(values = c("Base" = "darkgrey",
"dog" = "seagreen4",
"cat" = "seagreen3",
"lion" = "seagreen2",
"Apple" = "seagreen1",
"Banana" = "steelblue4",
"Orange" = "steelblue3",
"Pear" = "steelblue2",
"Grape" = "steelblue1",
"Kiwi" = "purple4",
"Passion" = "purple1")) +
geom_errorbar(aes(xmin = rel_lower, xmax = rel_upper), position = position_dodge2(width = 1, preserve = "single")) +
labs(title = "Average marginal component effect on choice probability") +
ylab("Attribute Levels") +
xlab("Percentage change in probability of choosing drug relative to base case") +
facet_grid(attribute ~ .,
scales = "free_y",
space = "free_y",
drop = TRUE) + ############################
scale_x_continuous(breaks = seq(floor(x_range[1]), ceiling(x_range[2]), by = 0.2), # Adjust breaks based on the range
minor_breaks = seq(floor(x_range[1]), ceiling(x_range[2]), by = 0.1), # Adjust minor breaks
labels = percent_format()) + # Format labels as percentages
theme(axis.text.x = element_text(angle = 0, vjust = 0.5, hjust = 0.5, size = 8),
axis.text.y = element_text(size = 8),
axis.title.x = element_text(size = 8, margin = margin(t = 15)), # Adjust margin to move the title down
axis.title.y = element_text(size = 8),
legend.text = element_text(size = 8),
legend.title = element_text(size = 8),
plot.title = element_text(size = 8),
legend.position = "bottom",
strip.text = element_text(size = 8, color = "black"),
panel.grid.major.x = element_line(color = "grey80", size = 0.25))+ # Major vertical grid lines
# panel.grid.minor.x = element_line(color = "grey80", size = 0.25)) + # Minor vertical grid lines
guides(fill = guide_legend(title = "Scenario", label = "Scenario", ncol = 2))
Plot5 <- tag_facet(Plot5) # Add in the a and b labels
Plot5