我有一个跨多行的y轴标题。 y轴标题上的每一行应从同一位置开始(最好在可能会使轴标题长度变化且绘图大小变化的函数中起作用)。
参见图表:
更新:
结合使用str_pad
和side = "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 character和Changing fonts in ggplot2上的线程。尽管仍然会希望使用不限制字体类型的解决方案...
答案 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))