如何集中ggplot情节标题

问题描述 投票:3回答:4

以“lege artis”为中心的方式证明了ggplot中的情节标题 - plot.title = element_text(hjust = 0.5) - 将标题置于绘图区域之外,不包括轴标签。

当轴标签很长时,这可能会变得很难看,例如Mary Poppins Soundtrack中的歌曲曲线与他们的角色长度。

length of songs in Mary Poppins Soundrack

library(tidyverse)

mary_poppins <- data_frame(song = c("Overture", "Sister Suffragette", "The Life I Lead", "The Perfect Nanny", "A Spoonful of Sugar", "Pavement Artist", "Jolly Holiday", "Supercalifragilisticexpialidocious", "Stay Awake", "I Love to Laugh", "A British Bank", "Feed the Birds ", "Fidelity Fiduciary Bank", "Chim Chim Cher-ee", "Step in Time", "A Man Has Dreams", "Let's Go Fly a Kite"
))

mary_poppins <- mary_poppins %>%
  mutate(len = nchar(song))

ggplot(data = mary_poppins, aes(x = reorder(song, len), y = len)) +
  geom_col(fill = "firebrick") +
  coord_flip() +
  theme_light() +
  theme(axis.title.y = element_blank(),
        axis.text = element_text(size = rel(1.5)),
        plot.title = element_text(size = rel(2.5), face = "bold", hjust = 0.5, 
                                  margin = margin(t = 10, b = 20, unit = "pt"))) +
  ggtitle("Mary Poppins") +
  ylab("Lenght of title (characters)")

有没有办法将标题集中在总的情节区域,即。包括轴标签占用的区域?

r ggplot2 data-visualization
4个回答
4
投票

或者,您可以使用gridExtra::grid.arrangegrid::textGrob创建标题,而无需在视觉上填充它。这基本上创建了一个单独的绘图对象与您的标题并将其粘贴在顶部,不同于您的ggplot调用的内容。

首先将整个ggplot调用存储在变量中,例如p1

grid.arrange(textGrob("Mary Poppins", 
               gp = gpar(fontsize = 2.5*11, fontface = "bold")), 
             p1, 
             heights = c(0.1, 1))

你必须将你的theme()设置翻译成gpar()theme_light的基本大小是11,这是2.5 * 11来自的地方(和你的rel(2.5)的2.5)。

enter image description here

这里的优点是你知道你的标题将真正居中,而不仅仅是靠近眼睛。


1
投票

添加空格到中心标题的解决方案:

在标题后添加空格:

ggtitle(paste0("Mary Poppins", paste0(rep("", 30), collapse = " ")))

对于像这样的输出:

enter image description here

不是完美的解决方案,但有效。


1
投票

我找到的简短解决方案:

theme(plot.title = element_text(hjust = -0.2))

hjust参数控制从左对齐到y轴的距离。负值将文本向左移动


0
投票

如果你赶时间,在ggtitle中标题之后添加空格也会有效......

ggtitle("Mary Poppins                                 ") +

输出:Center Mary Poppins Title

© www.soinside.com 2019 - 2024. All rights reserved.