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日创建