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
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
