Best practice for multiple subtitles in ggplot2
Asked Answered
N

0

6

I'm trying to find a smart and stable way to place multiple subtitles on the same line, with one aligned to the left, the other one to the right. It should be a general solution as I'm

The most concise solution (IMO) that does exactly what I want with element_text(hjust = c(0, 1)) (see reprex below) is not officially supported and going into a deprecation cycle.

library(ggplot2)
ggplot(data = mtcars, aes(x = disp, y = mpg)) +
  geom_line() +
  labs(subtitle = c("left-aligned subtitle", "right-aligned subtitle")) +
  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.

Created on 2024-05-14 with reprex v2.1.0

Using grobs seems somewhat flimsy and it's not too easy to get the position of the subtitle from the internals.

Another solution would be to use annotations outside the plotting area but then again that requires usage of coord_cartesian() with clip = "off" and the documentation mentions that

In most cases, the default of "on" should not be changed, as setting clip = "off" can cause unexpected results.

So what might a good and stable solution look like?

Nodababus answered 14/5 at 8:27 Comment(6)
Does this answer your question? https://mcmap.net/q/1918645/-proper-way-to-pass-vectorized-input-to-element_textMolybdic
@Molybdic That might be it, thank you! Somewhat confused about the way hjust works in ggtext's element_text(), however, it seems c(0, 1) is not quite the same as in ggplot's version.Nodababus
Not sure why c(0, 1) isn't working with element_markdown() as expected - I'll look into itMolybdic
Cool, otherwise I'll ask on Github.Nodababus
I mean it will work with hjust = c(1, 5)) but that's not exactly how I'd expect it to work.Nodababus
FYI: see github.com/wilkelab/ggtext/issues/116Nodababus

© 2022 - 2024 — McMap. All rights reserved.