ggtitle 中的自动换行

Fra*_*sca 3 r line-breaks ggplot2 ggtitle

有没有办法在命令中强制自动换行ggtitle

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

我通过\n提前手动插入(或换行)遇到了一种可能性(详细信息在这里:改进使用 \n 并向右延伸的 ggplot 中多行标题的编辑)。在那里,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)
Run Code Online (Sandbox Code Playgroud)

你可以在这里找到一张图片:https : //i.stack.imgur.com/6MMKF.jpg

您是否知道如何使sep = 操作员自动断线,或者是否有包/解决方法?谢谢!

teu*_*and 7

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`.
Run Code Online (Sandbox Code Playgroud)