I have a list of data frames that I use to make a list of ggplot
s, and then assemble into a grid of plots with cowplot
. I need to then attach a sha
Like so?
library(ggplot2)
library(cowplot)
theme_georgia <- function(...) {
theme_gray(base_family = "Georgia", ...) +
theme(plot.title = element_text(face = "bold"))
}
title_theme <- calc_element("plot.title", theme_georgia())
ggdraw() +
draw_label(
"Socio-economic measures",
fontfamily = title_theme$family,
fontface = title_theme$face,
size = title_theme$size
)
Created on 2018-06-21 by the reprex package (v0.2.0).
@Claus Wilke's solution got the job done, but I was inspired to write a wrapper function around draw_label
to get the styling necessary to mimic a theme element. I'm posting here in case it's of use to anybody else, though this might be a weird use case.
This function takes a theme function or, if theme
is omitted, gets the current theme from theme_get
. It also takes the name of a theme element, such as "plot.title"
, from which it gets the styling with calc_element
. All the requisite arguments are passed to cowplot::draw_label
, along with anything else in ...
such as x
or hjust
.
library(tidyverse)
library(cowplot)
draw_label_theme <- function(label, theme = NULL, element = "text", ...) {
if (is.null(theme)) {
theme <- ggplot2::theme_get()
}
if (!element %in% names(theme)) {
stop("Element must be a valid ggplot theme element name")
}
elements <- ggplot2::calc_element(element, theme)
cowplot::draw_label(label,
fontfamily = elements$family,
fontface = elements$face,
colour = elements$color,
size = elements$size,
...
)
}
title <- ggdraw() +
draw_label_theme("Socio-economic measures",
theme = theme_georgia(), element = "plot.title",
x = 0.05, hjust = 0, vjust = 1)
subtitle <- ggdraw() +
draw_label_theme("By census tract, 2016",
theme = theme_georgia(), element = "plot.subtitle",
x = 0.05, hjust = 0, vjust = 1)
Now the only hard part is lining things up neatly in the rel_heights
, which I could mess around with more here. There might be positioning information to pull out of the theme and use to set the heights.
plot_grid(title, subtitle, gridded, ncol = 1, rel_heights = c(0.1, 0.1, 1))