3

I'm trying to add a second caption in my ggplot2 graph. Similar to how this graphic was done by this economist

enter image description here

Here is a basic plot I made where I know how to add one caption on the bottom right, but how can I add another one to the bottom left

ggplot(mtcars, aes( mpg, hp)) +
  geom_point() +
  labs(title = "MTCARS MPG ~ HP",
       caption = "Source: mtcars dataset") 
tjebo
  • 21,977
  • 7
  • 58
  • 94
RL_Pug
  • 697
  • 7
  • 30

1 Answers1

3

As usual you have two options - either annotation outside the plot, or you create two (or three!) plots and combine them.

Both options require a bit of trial and error. Hopefully you won't need that very often and not need to fully automate it depending on different scales etc.

library(ggplot2)
library(patchwork)

textframe <- data.frame( #making the frame for the text labels.
    x = c(-Inf, Inf),
    y = -50,
    labels = c("Source1: mtcars dataset", "Source2: Not mtcars dataset"))

option 1 annotation outside the plot

# requires manual trial and error with plot margin and y coordinate... 
# therefore less optimal

  ggplot(mtcars, aes( mpg, hp)) +
  geom_point() +
    geom_text(data = textframe, aes(x, y, label = labels), hjust = c(0,1)) +
    coord_cartesian(ylim = c(0,350), clip = 'off') +
    theme(plot.margin = margin(b = 50, 5,5,5, unit = 'pt'))

option 2 Two plots, combining them. Here using patchwork. I personally prefer this option.

p1 <- 
  ggplot(mtcars, aes( mpg, hp)) +
  geom_point() 

p2 <- 
  ggplot(mtcars, aes( mpg, hp)) +
    geom_blank() +
    geom_text(data = textframe, 
              aes(x, y = Inf, label = labels), 
              hjust = c(0,1), 
              vjust = 1) +
    theme_void() 

  p1/p2 +plot_layout(heights = c(1, 0.1))

Created on 2020-04-04 by the reprex package (v0.3.0)

tjebo
  • 21,977
  • 7
  • 58
  • 94
  • How do you make "textframe" if the x-axis is dates? Because -Inf won't work with dates – arv Nov 02 '20 at 12:37
  • 1
    @arv - maybe worth a follow up question. if you decide to post, please don't forget to link to this question. – tjebo Nov 04 '20 at 14:48