【问题标题】:Add line break to axis labels and ticks in ggplot在ggplot中为轴标签和刻度添加换行符
【发布时间】:2013-11-21 14:09:10
【问题描述】:

我正在寻找一种在绘图的 x 轴上使用长变量名称的方法。当然,我可以使用较小的字体或稍微旋转它们,但我希望它们保持垂直且可读。

举个例子:

df <- data.frame(a=LETTERS[1:20], b=rnorm(20), c=rnorm(20), d=rnorm(20))
df_M <- melt(df, id="a")
plot <- ggplot(data=df_M, 
               aes(x=variable, y=a, fill=value)) + 
          geom_tile() + 
          scale_fill_gradient(low="green", high="red")
plot

这里的 x 轴只是字母,但如果我想使用全名,名称会占用不成比例的空间:

    plot +  
      theme(axis.text.x=element_text(angle=90)) + 
      scale_x_discrete(breaks=unique(df_M$variable), 
                       labels=c("Ambystoma mexicanum", 
                                "Daubentonia madagascariensis",
                                "Psychrolutes marcidus"))

所以我想在标签中添加一个换行符。最好在 ggplot2 中使用,当然也欢迎使用其他解决方案。

谢谢!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以添加自己的格式化程序(请参阅scales 包了解更多示例)。在这里,我将 x 标签中的任何空格替换为新行。

    addline_format <- function(x,...){
        gsub('\\s','\n',x)
    }
    
    myplot + 
        scale_x_discrete(breaks=unique(df_M$variable), 
        labels=addline_format(c("Ambystoma mexicanum", 
                            "Daubentonia madagascariensis", "Psychrolutes marcidus")))
    

    【讨论】:

    • 太好了,谢谢。从来没有想过,正是我需要的!
    • 不确定为什么需要addline_format 函数。不能直接在标签中指定换行符吗?例如,c("Ambystoma\nmexicanum",...
    • 甚至不需要输入标签,这工作scale_x_discrete(labels=function(x){sub("\\s", "\n", x)})
    【解决方案2】:

    通过str_replace_all(),将'foo_your_symbol_delim' 替换为空格分隔符' '

    通过str_wrap 来自stringr 库,宽度预先指定为40,在空格分隔符' ' 处拆分,包装碎片并粘贴

    library(stringr)
    ...
    + scale_x_discrete(labels = function(x) str_wrap(str_replace_all(x, "foo" , " "),
                                                     width = 40))
    

    【讨论】:

    • 因为我一直在寻找类似的解决方案并创建了这个更通用、更高效的解决方案。
    • 尝试改进旧问题的答案并没有错!也就是说,如果您使用不那么简洁的写作风格,您的答案会得到进一步改进。
    【解决方案3】:

    如果您不想在每个空格处休息,您也可以在对 scale_x_continuous 的调用中使用\n(新行):

    my.labels <- c("Ambystoma\nmexicanum",
                   "Daubentonia madagascariensis", 
                   "Psychrolutes marcidus") # first create labels, add \n where appropriate.
    
    myplot + 
        scale_x_discrete(labels= my.labels)
    

    请注意,使用换行命令 (\n) 时,只有名字 (Ambystoma mexicanum) 会中断。

    【讨论】:

      【解决方案4】:

      除了乔的回答之外,这也有效

      myplot + scale_x_discrete(labels = c("Ambystoma\nmexicanum")
      

      【讨论】:

      • 在回答一个老问题时,如果您包含一些上下文来解释您的答案如何提供帮助,那么您的答案将对其他 StackOverflow 用户更有用,特别是对于已经有一个已接受答案的问题。请参阅:How do I write a good answer
      【解决方案5】:

      我还要补充@SoilSciGuy 的回答,如果您只想修改一个标签,您可以在scale_x_discrete() 内进行。

      myplot + scale_x_discrete(labels = c("Ambystoma mexicanum" = "Ambystoma\nmexicanum")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-11
        • 2021-09-12
        • 2021-12-19
        • 1970-01-01
        相关资源
        最近更新 更多