以“lege artis”为中心的方式证明了ggplot中的情节标题 - plot.title = element_text(hjust = 0.5) - 将标题置于绘图区域之外,不包括轴标签。
当轴标签很长时,这可能会变得很难看,例如Mary Poppins Soundtrack中的歌曲曲线与他们的角色长度。
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)")
有没有办法将标题集中在总的情节区域,即。包括轴标签占用的区域?
或者,您可以使用gridExtra::grid.arrange
和grid::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)。
这里的优点是你知道你的标题将真正居中,而不仅仅是靠近眼睛。
我找到的简短解决方案:
theme(plot.title = element_text(hjust = -0.2))
hjust参数控制从左对齐到y轴的距离。负值将文本向左移动