35
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)

我可以将情节标题设置为环绕并缩小文本以适应情节吗?

4

3 回答 3

61

您必须手动选择要换行的字符数,但是 和 的组合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))
于 2010-10-14T16:34:09.953 回答
15

仅用于评论中提到的更新已被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:使用包中str_wrap的选项stringr并设置您的理想宽度:

 library(stringr)
 ggplot(data = cars, aes(x = speed, y = dist)) +
      geom_smooth() +
      labs(title = str_wrap(my_title, 60))

选项2:使用@Richie https://stackoverflow.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://stackoverflow.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))
于 2020-09-01T12:28:19.330 回答
11

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

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

其实你文字的方方面面都具备了theme_text功能。

于 2010-04-13T22:58:42.040 回答