在ggplot2中对齐多行轴标题

时间:2019-02-22 22:19:29

标签: r ggplot2

我有一个跨多行的y轴标题。 y轴标题上的每一行应从同一位置开始(最好在可能会使轴标题长度变化且绘图大小变化的函数中起作用)。

参见图表:

Gist with code of function.

更新:
结合使用str_padside = "right"和文本element_text(family="mono")(字符之间的点大小一致的字体)也可以使用,例如:

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

reprex package(v0.2.1)于2019-02-23创建

如果您不想使用默认的mono字体“ TT Courier New”,这里是which fonts have the same width for every characterChanging fonts in ggplot2上的线程。尽管仍然会希望使用不限制字体类型的解决方案...

1 个答案:

答案 0 :(得分:2)

这似乎有点hack,但是与使用“ true” plotmath相比,将paste0与“ \ n”一起使用也有点hack,因此也许会很有用。用前导空格填充每行,然后使用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