我正在尝试在ggplot2图形中添加第二个标题。类似于这位经济学家的图表]
这是我制作的基本情节,我知道如何在右下角添加一个标题,但是如何在左下角添加另一个标题
ggplot(mtcars, aes( mpg, hp)) +
geom_point() +
labs(title = "MTCARS MPG ~ HP",
caption = "Source: mtcars dataset")
通常,您有两个选择-在图外进行注释,或者创建两个(或三个!)图并将其组合。
两个选项都需要反复试验。希望您不会经常需要此方法,也不需要根据不同的比例将其完全自动化。
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))
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLmltZ3VyLmNvbS8xNVdialBVLnBuZyJ9” alt =“”>
由reprex package(v0.3.0)在2020-04-04创建