如何在ggplot2图中具有两个源标题? [英] How to have two source captions in a ggplot2 graph?
问题描述
我正在尝试在ggplot2图形中添加第二个标题.类似于这位经济学家的图表
I'm trying to add a second caption in my ggplot2 graph. Similar to how this graphic was done by this economist
这是我制作的一个基本情节,我知道如何在右下角添加一个标题,但是如何在左下角添加另一个标题
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")
推荐答案
与往常一样,您有两个选择-在图外进行注释,或者创建两个(或三个!)图并将它们组合起来.
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"))
图外的
选项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
.我个人更喜欢此选项.
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))
由 reprex软件包(v0.3.0)创建于2020-04-04 sup>
Created on 2020-04-04 by the reprex package (v0.3.0)
这篇关于如何在ggplot2图中具有两个源标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!