Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Align ggplot y axis labels along common middle line, across facets

When y-axis labels are of different length, element_text(hjust = .5) aligns the labels around a common middle line within facets, rather than across all the labels.

An example:

library(tidyverse)

t1 <- tibble(
  labs = c(
    "A short label",
    "Second short label",
    "This is a medium length label",
    "This is also a medium length",
    "Now, this label is actually quite long, really long",
    "This label is also actually quite long, really long"
    ) %>% 
    fct_inorder %>% 
    fct_rev,
  facs = str_c(
    "facet", 1:3
    ) %>% 
    rep(each = 2),
  x = runif(6)
  )

t1 %>% 
  ggplot(
    aes(
      x, labs
    )
  ) +
  geom_point() +
  facet_grid(
    vars(facs), 
    scales = "free_y"
  ) +
  labs(
    x = "",
    y = ""
  ) +
  theme(
    axis.text.y = element_text(hjust = .5)
  )

should return

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

How do I get the y-axis labels to be middle aligned along a common axis?

>Solution :

You could add the following dplyr::mutate to the tibble: mutate(labs = str_pad(labs, max(str_width(labs)), side = "both")) to add padding to the strings so they all have the same apparent length.

library(tidyverse)

t1 <- tibble(
  labs = c(
    "A short label",
    "Second short label",
    "This is a medium length label",
    "This is also a medium length",
    "Now, this label is actually quite long, really long",
    "This label is also actually quite long, really long"
  ) %>% 
    fct_inorder %>% 
    fct_rev,
  facs = str_c(
    "facet", 1:3
  ) %>% 
    rep(each = 2),
  x = runif(6)
) |> 
  mutate(labs = str_pad(labs, max(str_width(labs)), side = "both"))

t1 %>% 
  ggplot(
    aes(
      x, labs
    )
  ) +
  geom_point() +
  facet_grid(
    vars(facs), 
    scales = "free_y"
  ) +
  labs(
    x = "",
    y = ""
  ) +
  theme(
    axis.text.y = element_text(hjust = .5)
  )

Created on 2023-07-17 with reprex v2.0.2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading