如何在 ggplot2 图中添加两个源标题?

3

我正在尝试在我的ggplot2图中添加第二个标题。 类似于这位经济学家所做的图表。

enter image description here

这是我制作的一个基本图,我知道如何在右下角添加一个标题,但是如何在左下角添加另一个标题呢?

ggplot(mtcars, aes( mpg, hp)) +
  geom_point() +
  labs(title = "MTCARS MPG ~ HP",
       caption = "Source: mtcars dataset") 
1个回答

3
作为通常的做法,你有两个选择 - 要么在图外进行注释,要么创建两个(或三个!)图并将它们合并。
这两个选项都需要一些试错。希望你不需要经常这样做,并且不需要根据不同的比例完全自动化它。
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"))

选项1:图外标注

# 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'))

选项2 两个图表,将它们组合起来。这里使用 patchwork。我个人更喜欢这个选项。

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))

该内容由 reprex包 (v0.3.0) 在2020年4月4日创建


如果x轴是日期,如何创建“textframe”?因为-Infinity不能与日期一起使用。 - arv
1
@arv - 或许值得追问。如果您决定发布,请不要忘记链接到这个问题。 - tjebo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接