I am plotting the results of a 2 x 2 factorial design (see image). On the x axis, ggplot shows the levels of both variables at each tick (e.g., "UK.Female"). What I want is the axis to be arranged hierarchically in two rows (lower row: Female - Male; upper row: UK - US - UK - US) like in the image.

This is my code for the plot:
ggplot(data_full, aes(x = interaction(country, gender), y = response, fill = gender)) +
geom_violin() + stat_summary()
You could work around this by using facets with zero spacing:
df <- data.frame(x = rnorm(100),
catA = rep(c("M", "F"), each = 50),
catB = rep(c("A", "B"), 50))
ggplot(df, aes(catA, x)) +
geom_violin() +
facet_grid(~ catB, switch = "x") +
theme(panel.spacing.x = grid::unit(0, "mm"),
strip.placement = "outside",
strip.background = element_blank())

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With