【发布时间】:2018-09-23 18:53:26
【问题描述】:
默认对齐方式是 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")
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))
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))
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
@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 )
由reprex package (v0.2.1) 于 2018 年 9 月 24 日创建
【问题讨论】:
-
一种方法是将带有标题的 textGrob 绑定到情节。这是一种使用 grid.arrange 为您工作的方法
gridExtra::grid.arrange( top=grid::textGrob("This title is roughly center-aligned to panel"), p ) -
@user20650,这看起来不错,我之前看过 Grid.arrange 但不是这样。如果我为字幕堆叠另一个 textGrob,是否有一个参数可以让我摆脱填充?如果我使用您的
gridExtra::grid.arrange(top=grid::textGrob("This title is roughly center-aligned to panel"), grid::textGrob("subtitle"), p ),则 textgrobs 肯定位于整个面板的中心,但垂直间距很大。有什么办法可以减少这种情况?理想情况下,我希望将标题和副标题文本分开,这样我就可以设置不同的样式。 -
grid.arrange( top=grobTree(textGrob("This title"), textGrob("\n\nThis subtitle", gp=gpar(cex=0.8))), p, padding=unit(2, "line") ):不确定随着标题字体大小等的增加,它会有多强大。 -
@user20650,谢谢!现在,我想我会接受你的建议。它实际上工作得很好,因为标题和字幕的字体大小在所有图表中都是标准化的,所以一旦我找到了正确数量的新行来放入字幕文本,它就不需要更改。我会用你的代码更新我的问题。