" 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)")
有没有办法将标题集中在总情节区域上,即。包括轴标签占据的区域?
答案 0 :(得分:4)
或者,您可以使用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)。
这里的优点是你知道你的头衔将真正居中,而不仅仅是靠近眼睛。
答案 1 :(得分:2)
正如我在本质上duplicate question中回答的那样,您可以使用patchwork
库,它是plot_annotation
,因此您将拥有:
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))) +
patchwork::plot_annotation("Mary Poppins",
theme = theme(plot.title = element_text(size = rel(2.5), face = "bold", hjust = 0.5,
margin = margin(t = 10, b = 20, unit = "pt")))) +
ylab("Lenght of title (characters)")
由于plot_annotation
是为多面板图设计的,因此它不会继承正在构造的图的主题,因此您需要单独提供它。但是,它将尊重任何全球主题。
(希望)生成的图是您所需要的。
答案 2 :(得分:1)
解决方案将空格添加到中心标题:
在标题后面添加空格:
ggtitle(paste0("Mary Poppins", paste0(rep("", 30), collapse = " ")))
对于这样的输出:
不完美的解决方案,但有效。
答案 3 :(得分:1)
我找到的简短解决方案:
theme(plot.title = element_text(hjust = -0.2))
hallow 参数控制从左对齐到y轴的距离。负值会将文本向左移动
答案 4 :(得分:1)
解决问题的一种简单方法是在地块中添加以下内容:
theme(plot.title.position = 'plot',
plot.title = element_text(hjust = 0.5))
第一部分告诉ggplot
使用整个绘图作为居中的参考,第二部分告诉标题为居中。
答案 5 :(得分:0)