Bryan Shalloway
Bryan Shalloway

Reputation: 908

Align multi-line axis title in ggplot2

I have a y-axis title that goes across multiple lines. Each line on the y-axis title should start at the same location (prefer it works within a function that may have axis title length vary and plot size change).

See chart:

Gist with code of function.

UPDATE:
Using str_pad, with side = "right" and text element_text(family="mono") (font with a consistent point size across characters) also works, e.g.:

library(tidyverse)
quo_name_exprs_rplcmnt <- c(strrep("a", 9), strrep("b", 6), strrep("c", 3))
y_level <- c("Box and whiskers: ", "Coarse means: ", "Coarse means:")

(y_axis <- paste0(y_level, quo_name_exprs_rplcmnt) %>% 
  str_pad(width = max(str_length(.)), side = "right") %>% 
  str_c(collapse = "\n"))
#> [1] "Box and whiskers: aaaaaaaaa\nCoarse means: bbbbbb       \nCoarse means:ccc           "

ggplot() + 
  labs(y = y_axis)+
  theme(text = element_text(family="mono"))

Created on 2019-02-23 by the reprex package (v0.2.1)

If you don't want to use the default mono font of "TT Courier New", here are threads on which fonts have the same width for every character and Changing fonts in ggplot2 . Though would still prefer a solution that does not constrain font type...

Upvotes: 2

Views: 1701

Answers (1)

IRTFM
IRTFM

Reputation: 263499

This seems like a bit of a hack, but then using paste0 with "\n"'s is also a bit of hack compared with using "true" plotmath, so perhaps it will be useful. Pad each of the lines with leading spaces and then use hjust=0

 # change the y value to --->
y = paste0(     "                                 ","Box and whiskers: ", quo_name(y_expr),
           "\n","                                 ","Granular means: ", quo_name(gran_expr),
           "\n","                                 ","Coarse means: ", quo_name(coarse_expr), "     ")


 flights %>% 
   box_box_box_plot(arr_delay_log, carrier, quarter, day)+
   ggtitle("Quarter 2 typically has the worst delays")+theme(axis.title.y=element_text(hjust=0))

enter image description here

Upvotes: 3

Related Questions