Using ggplot2
, I'd like to have two subtitles on the same line, under the title, but one left-aligned and one right-aligned for a facetted plot like the one below.
I can have a subtitle left-aligned:
p <- ggplot(mtcars, aes(mpg, hp)) +
geom_point() +
facet_grid(am~.) +
theme(plot.title=element_text(hjust=0.5))
p + labs(title="Data: mtcars", subtitle="Subtitle (left-aligned)")
or right-aligned,
p + labs(title="Data: mtcars", subtitle="Subtitle (right-aligned)") +
theme(plot.subtitle=element_text(hjust=1))
but I can't seem to have both, unless I combine them with an arbitrarily large number of spaces in between (which is how I made the plot above). But I don't like that solution. Is there another way?
Hacky and spooky, but works. You can pass a vector to subtitle=
and set the alignment for each element by passing a vector to hjust=
(which of course is not officially supported):
library(ggplot2)
p <- ggplot(mtcars, aes(mpg, hp)) +
geom_point() +
facet_grid(am ~ .) +
theme(plot.title = element_text(hjust = 0.5))
p + labs(
title = "Data: mtcars",
subtitle = c("Subtitle (left-aligned)", "Subtitle (right-aligned)")
) +
theme(plot.subtitle = element_text(hjust = c(0, 1)))
#> Warning: Vectorized input to `element_text()` is not officially supported.
#> ℹ Results may be unexpected or may change in future versions of ggplot2.