rggplot2ggridges

Vertically centered axis text in R ggplot2


I am plotting multiple areas using ggplot2 and ggridges. I want to vertically center the y-axis texts. Is there a way to achieve this in an automated way? As a manual approach, I am specifying at the moment an offset via theme(axis.text.y = element_text(vjust = -2.5)). However, ideally I want to simply center it to the respective area of the different Species, irrespective of the size of the plot. If there is another approach to achieve a similar plot without ggridges, this would also be fine.

example

library(ggplot2)
library(ggridges)

ggplot(iris, aes(x = Sepal.Length, y = Species)) +
  geom_density_ridges(scale = 1) +
  theme(axis.text.y = element_text(vjust = -2.5))

Solution

  • One hack could be to use facets, move the labels to the side, and remove the padding so they're halfway up the data.

    The ordering in your original version was upward ascending (like default y axes in ggplot2), but with facets the order will be downward ascending (in english "reading" order), so you would need to reverse your y axis ordering (e.g. with forcats::fct_rev()) to get the original ordering.

    ggplot(iris, aes(x = Sepal.Length, y = Species)) +
      geom_density_ridges(scale = 1) +
      facet_grid(vars(Species), scales = "free_y", switch = "y") +
      scale_y_discrete(expand = expansion(add = c(0,0))) +
      theme(axis.text.y = element_blank(),
            axis.ticks.y = element_blank(),
            strip.background = element_blank(),
            strip.text.y.left = element_text(angle = 0))
    

    enter image description here