在ggplot2中使用labeller=label_wrap将长轴标签换行

81
我想自动换行ggplot2中的标签,即在长标签处插入换行符。在这里写了如何编写一个函数(1)实现它,但遗憾的是我不知道在我的代码(2)中放置labeller=label_wrap的位置。 这里 编写了该函数的说明。
label_wrap <- function(variable, value) {
  lapply(strwrap(as.character(value), width=25, simplify=FALSE), 
         paste, collapse="\n")
}

(2) 代码示例

df = data.frame(x = c("label", "long label", "very, very long label"), 
                y = c(10, 15, 20))

ggplot(df, aes(x, y)) + geom_bar(stat="identity")

未换行的长标签直方图

我想要对这里一些较长的标签进行换行。


为什么不在ggplot2之外的标签上应用strwrap函数呢? - baptiste
我是R的新手。我该如何在外部应用strwrap函数? - Til Hund
请提供一个可重现的示例。 - Max Ghenis
4个回答

212

不需要使用label_wrap函数,而是使用stringr包中的str_wrap函数。

由于您没有提供数据框df,因此我创建了一个简单的数据框,其中包含您的标签。然后,对这些标签应用str_wrap函数。

library(ggplot2)
library(stringr)

df = data.frame(x = c("label", "long label", "very, very long label"), 
                y = c(10, 15, 20))
df

df$newx = str_wrap(df$x, width = 10)
df

现在将标签应用于ggplot图表:第一个图表使用原始标签;第二个图表使用修改后的标签;对于第三个图表,标签在调用ggplot时进行了修改。

ggplot(df, aes(x, y)) + 
  xlab("") + ylab("Number of Participants") +
  geom_bar(stat = "identity") 

ggplot(df, aes(newx, y)) + 
  xlab("") + ylab("Number of Participants") +
  geom_bar(stat = "identity")

ggplot(df, aes(x, y)) + 
  xlab("") + ylab("Number of Participants") +
  geom_bar(stat = "identity") +
  scale_x_discrete(labels = function(x) str_wrap(x, width = 10))

在这里输入图像描述


这个解决方案似乎非常接近我的问题。但是,如果每三个图形有不同的标签,我需要定义三个不同的function(x)才能使用str_wrap吗? - Til Hund
很抱歉,我不明白你的问题。第二次调用ggplot是正确的方法。也就是说,在调用ggplot之外应用str_wrap。如果你有其他包含长标签的变量,也要对这些变量应用str_wrap。 - Sandy Muspratt
我认为我们快要完成了,但我不太明白如何将str_wrap应用于所有变量,因此图表(约25个)具有完全不同的标签(请再次参见上面的示例代码)。 - Til Hund
1
scale_x_discrete(labels = str_wrap(c("label", "long label", "very, very long label"), width = 10)) - Sandy Muspratt
3
非常棒,@SandyMuspratt。备注:用“变量”和“数值”来定义你的数据框,而不是“x”和“y”,这样就会清楚地看到语法是“scale_x_discrete(labels = function(x) str_wrap(x, width = 10))”,我的第一次尝试错误地使用了“x”而不是“变量”。 - PatrickT
显示剩余2条评论

62

"scales"包含一个非常类似于Claude和Leonardo的wrap_format函数。

library(scales)
ggplot(df, aes(x, y)) + geom_bar(stat = "identity") + 
    labs(x = "", y = "Number of Participants") + 
    scale_x_discrete(labels = wrap_format(10))

10
与Sandy的解决方案相比,这种方法的优势在于它保留了因子的顺序。 - AndrewMinCH

16

这里有另一种不涉及 stringr 库的方法:

ggplot(df, aes(x, y)) + 
  xlab("") + ylab("Number of Participants") +
  geom_bar(stat = "identity") +
  scale_x_discrete(labels = function(x) lapply(strwrap(x, width = 10, simplify = FALSE), paste, collapse="\n"))

电话的位置:

lapply(strwrap(x, width = 10, simplify = FALSE), paste, collapse="\n")

将标签进行动态拆分的工作。其结果与第一个答案中的相同。


1
希望对@Claude的回答有所改进:
get_wraper <- function(width) {
    function(x) {
        lapply(strwrap(x, width = width, simplify = FALSE), paste, collapse="\n")
    }
}

ggplot(df, aes(x, y)) + geom_bar(stat = "identity") + 
    labs(x = "", y = "Number of Participants") + 
    scale_x_discrete(labels = get_wraper(10))

3
@Leonardo_Fontenelle 只需要一个函数 function(x,width) 就足够了。 - timat

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