首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >R: ggplot2,我可以将绘图标题设置为环绕并缩小文本以适合绘图吗?

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

Stack Overflow用户
提问于 2010-04-14 01:35:54
回答 3查看 29.9K关注 0票数 33
代码语言:javascript
复制
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)

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-04-14 06:58:42

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

代码语言:javascript
复制
title.size<-10
r + geom_smooth() + opts(title = my_title,plot.title=theme_text(size=title.size))

实际上,您可以使用theme_text函数来查看文本的所有方面。

票数 11
EN

Stack Overflow用户

发布于 2010-10-15 00:34:10

您必须手动选择要换行的字符数,但是strwrappaste的组合可以满足您的需要。

代码语言:javascript
复制
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))
票数 60
EN

Stack Overflow用户

发布于 2020-09-01 20:28:19

正如评论中提到的那样,仅仅为了更新,opts就被弃用了。你需要使用labs,你可以这样做:

代码语言:javascript
复制
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选项并设置理想宽度:

代码语言:javascript
复制
 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提供的函数:

代码语言:javascript
复制
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想要避免的,但它可能很方便)

代码语言:javascript
复制
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中的相同)

代码语言:javascript
复制
ggplot(data = cars, aes(x = speed, y = dist)) +
  geom_smooth() +
  labs(title = my_title) +
  theme(plot.title = element_text(size = 10))
票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2631780

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档