Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping on the x axis in ggplot2

In ggplot I want to create subcategories on the x axis as in:

enter image description here

The solutions presented in Multirow axis labels with nested grouping variables don't work.

like image 450
Magdalena J Matysek Avatar asked Aug 02 '26 06:08

Magdalena J Matysek


1 Answers

Update to version 2.2.0 or higher of ggplot2. Then you can use some more features of the facet_wrap to build the graphic you are looking for. Here is an example:

library(ggplot2)
packageVersion("ggplot2")
# [1] ‘2.2.1’

dat <-
  data.frame(category = c("A", "A", "B", "B", "C", "C"),
             subcat   = c("S1", "S2", "S1", "S2", "S1", "S2"),
             value    = c(73, 57, 7, 23, 51, 87))

ggplot(data = dat) +
  aes(x = subcat, y = value, fill = subcat) +
  geom_bar(stat = "identity", width = 1) +
  geom_text(mapping = aes(label = paste0(value, "%")), vjust = -0.5) +
  facet_wrap( ~ category, strip.position = "bottom", scales = "free_x") +
  theme(panel.spacing = unit(0, "lines"),
        strip.background = element_blank(),
        strip.placement = "outside") +
  xlab("x-axis label")

enter image description here

like image 194
Peter Avatar answered Aug 04 '26 01:08

Peter