我有一个数据框列表,用于制作ggplot
s 列表,然后用cowplot
. 然后我需要附加一个共享标题、副标题和标题。我想以这样一种方式做到这一点,即这些标签将具有相同的主题元素(大小、字体等),就好像它们是由labs
而不是cowplot::draw_label
.
在我的实际情况中,我有几个等值线,每个都有自己的单位和比例,这就是为什么我不能只是刻面,而是需要构建彼此独立的图。
这是数据的简化版本,以及我加载的包:
library(tidyverse)
library(cowplot)
dfs <- list(
adults_no_diploma = structure(list(
tract = c("09003405100", "09003405200", "09003405300", "09003405401", "09003405402", "09003405500", "09003405600", "09003405700", "09003405800", "09003405900"),
value = c(0.08, 0.108, 0.095, 0.099, 0.105, 0.103, 0.161, 0.279, 0.056, 0.055)),
row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame")),
severe_cost_burden = structure(list(
tract = c("09003405100", "09003405200", "09003405300", "09003405401", "09003405402", "09003405500", "09003405600", "09003405700", "09003405800", "09003405900"),
value = c(0.128, 0.147, 0.165, 0.1, 0.151, 0.11, 0.179, 0.184, 0.14, 0.038)),
row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"))
)
我正在使用自定义主题(同样是简化版本):
theme_georgia <- function(...) {
theme_gray(base_family = "Georgia", ...) +
theme(plot.title = element_text(face = "bold"))
}
plots <- dfs %>%
imap(~{
ggplot(.x, aes(x = value)) +
geom_density() +
ggtitle(.y) +
theme_georgia()
})
gridded <- plot_grid(plotlist = plots, nrow = 1)
在cowplot
注释 vignette之后,我可以制作标题ggdraw() + draw_label("Socio-economic measures")
并手动设置字体大小等内容,但我更喜欢以某种方式将该标签定义为标题;也就是说,主题会将所有内容应用plot.title
到其中,创建字幕和标题也是如此。
我目前的解决方法是为标题和副标题制作一个空ggplot
的,对标题做同样的事情,然后用.labs
cowplot::plot_grid
title_gg <- ggplot() +
labs(title = "Socio-economic measures", subtitle = "By census tract, 2016") +
theme_georgia()
plot_grid(title_gg, gridded, ncol = 1, rel_heights = c(0.15, 1))
解决方法是好的,但我喜欢你得到的整洁和对齐draw_label
。我可以一个一个地添加这些主题元素来模仿标题:
title_theme <- ggdraw() +
draw_label("Socio-economic measures",
fontfamily = theme_georgia()$text$family,
fontface = theme_georgia()$plot.title$face, x = 0.05, hjust = 0)
plot_grid(title_theme, gridded, ncol = 1, rel_heights = c(0.2, 1))
我的问题是我是否可以结合这些方法来提取所有相关的主题元素并draw_label
快速提供它们,或者以某种方式告诉draw_label
这个东西是一个标题并且应该得到标题主题元素,而另一个东西是一个副标题,并且很快。我想像这样的某种魔法:
ggdraw() +
draw_label("Socio-economic measures", theme_georgia()$plot.title_elements)
或者:
ggdraw() +
draw_label("Socio-economic measures", type = "title") + theme_georgia()