r - ggtitle 中的自动换行

标签 r ggplot2 line-breaks ggtitle

有没有办法在 ggtitle 中强制自动换行命令?
作为 Shiny 应用程序的一部分,我使用不同的绘图和标题的输入变量。
不幸的是,其中一些变量值太长而无法显示。
我通过插入 \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)
您可以在这里找到图片:/image/6MMKF.jpg
你知道如何例如适应 sep = 运算符(operator)自动断行还是可能有包/解决方法?谢谢!

最佳答案

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`.

关于r - ggtitle 中的自动换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66105121/

相关文章:

r - 计算 ggplot 3.3.0 中 `scale_x_binned` 直方图的标签

javascript - 如何从文本区域获取换行符

r - 如何在R中高效地实现合并

r - 使用滚动连接通过引用更新

删除 ggplot2 中的绘图边距

php - 如何使用 ajax 通过 url 发布消息并仍然保留换行符?

java - 在数据库中存储带换行符的TextArea数据并以带换行符的相同格式显示

r - 如何平滑 r 中的 ecdf 图

r - 在 R 和 gnuplot 中绘制大量 x、y、z 点进行 3D 绘图,并在每个时间步提取 bmp/gif/png 文件

r - 显示轴刻度ggplot时隐藏 "20"年的 "20XX"