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)
我可以将绘图标题设置为环绕并缩小文本以适合绘图吗?
答案 0 :(得分:40)
您必须手动选择要包装的字符数,但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))
答案 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))