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

时间:2010-04-13 17:35:54

标签: r ggplot2 title word-wrap

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)

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

3 个答案:

答案 0 :(得分: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))

答案 1 :(得分:8)

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

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

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

答案 2 :(得分:3)

仅弃用注释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))