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

Joh*_*n 26 r title word-wrap ggplot2

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

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

Ric*_*ton 43

您必须手动选择要包装的字符数,但组合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))
Run Code Online (Sandbox Code Playgroud)

  • @Richie的这个答案在2018年对我有用; “实验室”取代了已弃用的“选择”。因此,SO应该让更多最新和更受好评的答案(信誉得分为x的人)浮动到顶部。 (2认同)

Use*_*321 12

仅针对评论中提到的更新已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"
Run Code Online (Sandbox Code Playgroud)

选项 1:使用包装中的str_wrap选项stringr并设置您的理想宽度:

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

选项 2:使用@Richie /sf/answers/275480061/提供的函数,如下所示:

wrapper <- function(x, ...) 
{
  paste(strwrap(x, ...), collapse = "\n")
}
ggplot(data = cars, aes(x = speed, y = dist)) +
      geom_smooth() +
      labs(title = wrapper(my_title, 60))
Run Code Online (Sandbox Code Playgroud)

选项 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)
Run Code Online (Sandbox Code Playgroud)

选项 4:减小标题的文本大小(如已接受的答案/sf/answers/184364141/

ggplot(data = cars, aes(x = speed, y = dist)) +
  geom_smooth() +
  labs(title = my_title) +
  theme(plot.title = element_text(size = 10))
Run Code Online (Sandbox Code Playgroud)


Dre*_*way 8

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

title.size<-10
r + geom_smooth() + opts(title = my_title,plot.title=theme_text(size=title.size))
Run Code Online (Sandbox Code Playgroud)

实际上,你所有方面的文字都带有这个theme_text功能.

  • 更新:我认为在最近的 ggplot 中,您只需使用“\n”即可添加标题 (2认同)