I have some y axis labels I want to have all the same spacing. The labels are composed of 2 variables and I'd like to put the correct spacing in between to the left variable is left aligned and the right variable is right aligned. I assumed this to be a trivial task and in fact doing so in a data.frame is easy using string padding functions from stringi package. However the plot does not have the desired alignment.
library(stringi)
library(tidyverse)
paster <- function(x, y, fill = ' '){
nx <- max(nchar(x))
ny <- max(nchar(y))
paste0(
stringi::stri_pad_right(x, nx, fill),
stringi::stri_pad_left(y, ny, fill)
)
}
plot_dat <- mtcars %>%
group_by(gear) %>%
summarize(
n = n(),
drat = mean(drat)
) %>%
mutate(
gear = case_when(
gear == 3 ~ 'three and free',
gear == 4 ~ 'four or more',
TRUE ~ 'five'
),
label = paster(gear, paste0(' (', n, ')'))
)
plot_dat
## # A tibble: 3 x 4
## gear n drat label
## <chr> <int> <dbl> <chr>
## 1 three and free 15 3.132667 three and free (15)
## 2 four or more 12 4.043333 four or more (12)
## 3 five 5 3.916000 five (5)
plot_dat %>%
ggplot(aes(x = drat, y = label)) +
geom_point()
Gives:
What I want is:
Your text strings are nicely spaced based on a monospace font (which is what R console uses).
Setting the axis label's font family to a monospace font will give the correct alignment:
ggplot(mtcars,
aes(x = drat, y = label)) +
geom_point() +
theme(axis.text.y = element_text(family = "mono"))
(Not the prettiest look, I know... But you get the basic idea. I haven't worked much with fonts in R & this is the only monospace font I can think of right now.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With