在ggplot中将图表标题居中的正确方法是使用plot.title = element_text(hjust = 0.5),它可以将标题居中于绘图区域但不包括轴标签。
当轴标签非常长时,例如下面这张《炮弹与小鸟》原声带歌曲与其字符长度的图表,这种方法可能会出现问题。
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)")
有没有一种方法可以将标题居中放置在总绘图区域上,即包括轴标签占用的区域?