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)我可以将绘图标题设置为环绕并缩小文本以适合绘图吗?
发布于 2010-04-14 06:58:42
我不认为ggplot2中有文本换行选项(我总是手动插入)。但是,您可以通过以下方式更改代码来缩小标题文本的大小:
title.size<-10
r + geom_smooth() + opts(title = my_title,plot.title=theme_text(size=title.size))实际上,您可以使用theme_text函数来查看文本的所有方面。
发布于 2010-10-15 00:34:10
您必须手动选择要换行的字符数,但是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))发布于 2020-09-01 20:28:19
正如评论中提到的那样,仅仅为了更新,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:使用stringr包中的str_wrap选项并设置理想宽度:
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:减小标题的文本大小(与accepted 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))https://stackoverflow.com/questions/2631780
复制相似问题