关于r:始终将ggplot标题居中于PANEL而不是PLOT

Consistently center ggplot title across PANEL not PLOT

默认对齐方式是使ggplot标题与plot.background元素左对齐。其他人注意到,您可以使用plot.title = element_text(hjust = 0.5)将标题居中。

  • 如何居中ggplot情节标题
  • ggplot2中的中心图标题

但是,我想使标题在整个面板中居中,而不是只针对情节。我过去通过修改hjust来推动标题以使其居中显示来完成此操作,但是hjust的值取决于标题的长度,这使得在我批量处理时进行设置非常繁琐产生图。

是否可以一致地将ggplot的标题元素设置为在panel.background中居中?

1
2
3
4
5
6
7
8
9
10
11
library(reprex)
library(tidyverse)
data(mtcars)

mtcars %>%
  rownames_to_column(var ="model") %>%
  top_n(8,wt) %>%
  ggplot(aes(x =model, y = wt))+
  geom_col()+
  coord_flip()+
  labs(title="This title is left-aligned to the plot")

> </p>
<div class=

1
2
3
4
5
6
7
8
mtcars %>%
  rownames_to_column(var ="model") %>%
  top_n(8,wt) %>%
  ggplot(aes(x =model, y = wt))+
  geom_col()+
  coord_flip()+
  labs(title="This title is center-aligned to the plot width.")+
  theme(plot.title = element_text(hjust = 0.5))

> </p>
<div class=

1
2
3
4
5
6
7
8
mtcars %>%
  rownames_to_column(var ="model") %>%
  top_n(8,wt) %>%
  ggplot(aes(x =model, y = wt))+
  geom_col()+
  coord_flip()+
  labs(title="Short title, still works")+
  theme(plot.title = element_text(hjust = 0.5))

> </p>
<div class=

1
2
3
4
5
6
7
8
mtcars %>%
  rownames_to_column(var ="model") %>%
  top_n(8,wt) %>%
  ggplot(aes(x =model, y = wt))+
  geom_col()+
  coord_flip()+
  labs(title="This title is roughly center-aligned to panel")+
  theme(plot.title = element_text(hjust = 0.37)) # I know I can adjust this, but it would require a manual fix each time

> </p>
<p>@ user20650的建议</p>
<div class=

1
2
3
4
5
6
7
8
9
10
p <- mtcars %>%
  rownames_to_column(var ="model") %>%
  top_n(8,wt) %>%
  ggplot(aes(x =model, y = wt))+
  geom_col()+
  coord_flip()+
  #labs(title="Short title, still works")+
  theme(plot.title = element_text(hjust = 0.5))

gridExtra::grid.arrange( top=grid::textGrob("This title is center-aligned to panel"),p  )