R:ggplot2,我可以将情节标题设置为环绕并缩小文本以适应情节吗?
Posted
技术标签:
【中文标题】R:ggplot2,我可以将情节标题设置为环绕并缩小文本以适应情节吗?【英文标题】:R: ggplot2, can I set the plot title to wrap around and shrink the text to fit the plot? 【发布时间】:2011-02-07 13:48:06 【问题描述】:library(ggplot2)
my_title = "This is a really long title of a plot that I want to nicely wrap \n and fit onto the plot without having to manually add the backslash n, but at the moment it does not"
r <- ggplot(data = cars, aes(x = speed, y = dist))
r + geom_smooth() + #(left)
opts(title = my_title)
我可以将情节标题设置为环绕并缩小文本以适应情节吗?
【问题讨论】:
【参考方案1】:您必须手动选择要换行的字符数,但 strwrap
和 paste
的组合将满足您的需求。
wrapper <- function(x, ...)
paste(strwrap(x, ...), collapse = "\n")
my_title <- "This is a really long title of a plot that I want to nicely wrap and fit onto the plot without having to manually add the backslash n, but at the moment it does not"
r +
geom_smooth() +
ggtitle(wrapper(my_title, width = 20))
【讨论】:
@Richie 的这个答案在 2018 年对我有用; 'labs' 替换已弃用的 'opts'。所以应该让最近和更多赞成的答案(由具有 x 声誉分数的人)浮到顶部。【参考方案2】:不推荐使用 cmets opts
中提到的更新。你需要使用labs
,你可以这样做:
library(ggplot2)
my_title = "This is a really long title of a plot that I want to nicely wrap \n and fit onto the plot without having to manually add the backslash n, but at the moment it does not"
选项 1:使用 stringr
包中的 str_wrap
选项并设置理想宽度:
library(stringr)
ggplot(data = cars, aes(x = speed, y = dist)) +
geom_smooth() +
labs(title = str_wrap(my_title, 60))
选项2:使用@Richie https://***.com/a/3935429/4767610 提供的函数,如下所示:
wrapper <- function(x, ...)
paste(strwrap(x, ...), collapse = "\n")
ggplot(data = cars, aes(x = speed, y = dist)) +
geom_smooth() +
labs(title = wrapper(my_title, 60))
选项 3:使用手动选项(当然,这是 OP 想要避免的,但它可能很方便)
my_title_manual = "This is a really long title of a plot that I want to nicely wrap \n and fit onto the plot without having to manually add \n the backslash n, but at the moment it does not"
ggplot(data = cars, aes(x = speed, y = dist)) +
geom_smooth() +
labs(title = my_title_manual)
选项 4:减小标题的文本大小(如接受的答案 https://***.com/a/2633773/4767610)
ggplot(data = cars, aes(x = speed, y = dist)) +
geom_smooth() +
labs(title = my_title) +
theme(plot.title = element_text(size = 10))
【讨论】:
【参考方案3】:我认为ggplot2
中没有文本换行选项(我一直只是手动插入\n)。但是,您可以通过以下方式更改代码来缩小标题文本的大小:
title.size<-10
r + geom_smooth() + opts(title = my_title,plot.title=theme_text(size=title.size))
其实你文字的方方面面都用theme_text
函数。
【讨论】:
opt
和 theme_text
已重命名:github.com/wch/ggplot2/wiki/New-theme-system
更新:我认为在最近的 ggplot 中,您可以简单地使用“\n”来添加标题以上是关于R:ggplot2,我可以将情节标题设置为环绕并缩小文本以适应情节吗?的主要内容,如果未能解决你的问题,请参考以下文章