rggplot2ggh4x

ggh4x: Rotate group labels with guide_axis_nested ggplot2


Hello I am using this package I found very handy

So this is the data:

df <- data.frame(
  x = LETTERS[1:16],
  group = rep(c("Group 1", "Group 2", "Group 3"), c(5, 3, 8)),
  value = rpois(16, 10)
)

And this is the code:

ggplot(df, aes(paste0(x, "&", group), value)) +
  geom_col() +
  guides(y = ggh4x::guide_axis_nested(delim = "&")) + coord_flip

This produces this plot:

enter image description here

How can I change the group labels (Group 1, Group 2, and Group 3) to be rotated 90 degrees to the left? Just the group labels.


Solution

  • To style the nested parts of the axis the ggh4x package provides the theme elements ggh4x.axis.nestline.x/y and ggh4x.axis.nesttext.x/y, i.e. to rotate the group labels you could use ggh4x.axis.nesttext.y like so

    library(ggplot2)
    library(ggh4x)
    
    set.seed(123)
    
    ggplot(df, aes(paste0(x, "&", group), value)) +
      geom_col() +
      guides(y = ggh4x::guide_axis_nested(delim = "&")) +
      coord_flip() +
      theme(
        ggh4x.axis.nesttext.y = element_text(
          angle = 90, hjust = .5
        )
      )