ggtitle中的自动换行

6

有没有一种方法可以在ggtitle命令中强制自动换行?

作为闪亮应用程序的一部分,我使用不同的绘图和输入变量作为标题。不幸的是,其中一些变量值太长无法显示。

我发现一种可能性是提前手动插入\n(或换行符)(详情请参见:Improve editing of multiline title in ggplot that uses \n and extends far to the right)。这里会建议类似ggtitle(paste("", title, "", sep = "\n"))的东西。

由于包含\n不仅容易出错,而且对于不同的绘图大小也不灵活,因此我正在寻找另一个可能性。

这是一个最小工作示例(从上面链接的lawyeR问题适应而来):

DF <- data.frame(x = rnorm(400))
title_example <- "This is a very long title describing the plot in its details. The title should be fitted to a graph, which is itself not restricted by its size."
plot <- ggplot(DF, aes(x = x)) + geom_histogram() +
  ggtitle(title_example)

你可以在这里找到一张图片:https://istack.dev59.com/6MMKF.webp 你有没有想过如何适应sep = 操作符以实现自动换行,或者是否有其他的包/解决方法?谢谢!

这是一个选项吗?https://dev59.com/y5Dea4cB1Zd3GeqPfLJo - masher
感谢@masher注意到这个相关的问题!由于这只是一个解决方法,我将使用@teunbrand建议的ggtext包,它非常好用! - Francesca
1个回答

11

ggtext包的文本元素可以帮助解决这个问题。element_textbox_simple()会自动将文本包装起来。试着调整一下图形设备窗口大小,它会自动适应!

library(ggplot2)
library(ggtext)

DF <- data.frame(x = rnorm(400))
title_example <- "This is a very long title describing the plot in its details. The title should be fitted to a graph, which is itself not restricted by its size."

ggplot(DF, aes(x = x)) + geom_histogram() +
  ggtitle(title_example) +
  theme(plot.title = element_textbox_simple())
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.


这对我非常有效,谢谢@teunbrand!如果有人想知道如何居中标题,“plot.title = element_textbox_simple(halign = 0.5)”就可以了。 - Francesca
还有没有办法让这个与字幕一起工作?当我使用ggtitle和字幕时,主标题会重叠在字幕上面。 - undefined
我对这个问题没有一个好的解决办法。 - undefined

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