R: ggplot2, can I set the plot title to wrap aroun

2020-01-29 06:58发布

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)

can I set the plot title to wrap around and shrink the text to fit the plot?

2条回答
ゆ 、 Hurt°
2楼-- · 2020-01-29 07:00

You have to manually choose the number of characters to wrap at, but the combination of strwrap and paste will do what you want.

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))
查看更多
疯言疯语
3楼-- · 2020-01-29 07:01

I do not think there is a text wrap option in ggplot2 (I have always just inserted \n manually). You can, however, shrink the size of the title's text by altering your code in the following way:

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

In fact, you all aspects of text with the theme_text function.

查看更多
登录 后发表回答