R:ggplot2,我可以将绘图标题设置为环绕并缩小文本以适合绘图吗?

问题描述 投票:24回答:2
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)

我可以设置绘图标题以包围并缩小文本以适应情节吗?

r ggplot2 title word-wrap
2个回答
8
投票

我不认为ggplot2中有文本换行选项(我总是只是手动插入\ n)。但是,您可以通过以下方式更改代码来缩小标题文本的大小:

title.size<-10
r + geom_smooth() + opts(title = my_title,plot.title=theme_text(size=title.size))

事实上,你使用theme_text函数的文本的所有方面。


40
投票

你必须手动选择要包装的字符数,但strwrappaste的组合将做你想要的。

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))
© www.soinside.com 2019 - 2024. All rights reserved.