在面板上始终将ggplot标题居中居中而不是PLOT

gra*_*ent 5 r ggplot2

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

但是,我想使标题在整个面板中居中,而不是只与情节相对。过去,我通过修改hjust来推动标题以使其居中显示,从而实现了这一点,但是的值hjust取决于标题的长度,这使得在批量生产图形时进行设置非常繁琐。

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

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")
Run Code Online (Sandbox Code Playgroud)

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))
Run Code Online (Sandbox Code Playgroud)

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))
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

@ user20650的建议

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  )
Run Code Online (Sandbox Code Playgroud)

reprex软件包(v0.2.1)创建于2018-09-24

小智 6

现在主题中有一个选项可以调用,plot.title.position将绘图标题置于整个绘图区域的中心,而不仅仅是绘图面板。如果您设置plot.title.position = "plot"theme(),它会将标题和副标题置于整个绘图区域的中心,而不仅仅是面板上方。

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 center-aligned to the plot width.")+
  theme(plot.title = element_text(hjust = 0.5),
        plot.title.position = "plot")
Run Code Online (Sandbox Code Playgroud)

该标题与绘图宽度中心对齐。


Wei*_*ong 3

一种方法是更改​​标题组的位置,使其从左边缘开始:

p <- 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") +
  theme(plot.title = element_text(hjust = 0.5))

library(gridExtra)
g <- ggplotGrob(p)
g$layout$l[g$layout$name == "title"] <- 1
grid::grid.draw(g)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述