仅用于评论中提到的更新已被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))