代码之家  ›  专栏  ›  技术社区  ›  Bryan Shalloway

在GGPROT2中对齐多行轴标题

  •  0
  • Bryan Shalloway  · 技术社区  · 7 年前

    我有一个Y轴标题横跨多行。Y轴标题上的每一行都应该在同一位置开始(更喜欢在一个可能具有轴标题长度变化和绘图大小变化的函数中工作)。

    见图表:

    Gist with code of function.

    更新:
    使用 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"))
    

    于2019-02-23由 reprex package (第5.2.1节)

    如果不想使用默认值 mono “TT Courier New”字体,以下是 which fonts have the same width for every character 和 Changing fonts in ggplot2 是的。虽然仍然希望一个解决方案,不限制字体类型…

    0 回复  |  直到 7 年前
        1
  •  2
  •   IRTFM    7 年前

    这看起来有点老套,但是 paste0 与使用“true”plotmath相比,使用“\n”也有点麻烦,所以也许它会有用。用前导空格填充每条线,然后使用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

    推荐文章