Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left and right align axis text with exact spacing between

Tags:

r

ggplot2

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:

enter image description here

What I want is:

enter image description here

like image 849
Tyler Rinker Avatar asked Aug 22 '17 04:08

Tyler Rinker


1 Answers

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

plot with properly aligned y axis labels

(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.)

like image 101
Z.Lin Avatar answered Oct 03 '22 22:10

Z.Lin