在ggplot中为轴标签和刻度添加换行符

38

我正在寻找一种在绘图的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,当然也欢迎其他解决方案。

谢谢!

5个回答

53
你可以添加自己的格式化程序(请参见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")))

输入图像描述


4
不确定为什么需要 addline_format 函数。难道不能直接在标签中指定换行吗?例如:c("Ambystoma\nmexicanum",... - Fuhrmanator
7
无需输入标签,使用此代码即可实现:scale_x_discrete(labels=function(x){sub("\\s", "\n", x)})。该代码的作用是将x轴离散变量标签中的空格替换为换行符,以使得标签更加易于阅读。注意不要改变原有的意思。 - Alex Thomas

36

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

使用stringr库中的str_wrap函数,预设宽度为40,在空格分隔符' '处分割,将片段包装并粘合

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

11
因为我正在寻找类似的解决方案并创建了一个更通用且高效的方案。 - MKJCKTZN
5
尝试改进旧问题的答案是没有错的!不过,如果您使用一种更加通俗易懂的写作风格,那么您的答案将会得到更大的改善。 - John Wickerson

25

如果您不想在每个空格处换行,您可以选择在调用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)将打破第一个名称(墨西哥大蠑螈)。

7

除了Joe的回答外,这个也可以工作。

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

当回答一个旧问题时,如果您包含一些上下文来解释您的答案如何帮助,特别是对于已经有被接受答案的问题,那么您的答案将对其他StackOverflow用户更有用。请参阅:如何撰写好的答案 - David Buck

5
我还要补充一点,如果你只想修改一个标签,你可以在 scale_x_discrete() 内部进行。这是与@SoilSciGuy的回答相补充的。
myplot + scale_x_discrete(labels = c("Ambystoma mexicanum" = "Ambystoma\nmexicanum")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接