我有一些 ggplot,我对其进行了调整以确保注释完全符合图的界限。例如:
现在我想将其中两幅图像并排放置。我尝试使用 grid.arrange 和 patchwork 来实现这一点,但图形的布局发生了变化,大概是因为它被放入了更小的空间:
一切都变得更加拥挤,点都挤在一起,因此更难阅读,并且注释框偏离了图表的一侧。
我想要做的是将画布扩展至刚好足够大,以使每个图形看起来与单独绘制时完全一样(即使用默认画布大小绘制时)。它可能需要比原来的两倍多一点,以便留出填充空间。我该如何实现这一点?
示例代码:
library(ggplot2)
library(ggtext)
library(tidyverse)
library(patchwork)
N <- 10000
rho = 0.5
mu <- c(0, 0)
sigma <- matrix(c(1, rho,
rho, 1 ),
nrow = 2, ncol = 2, byrow = TRUE)
vs = MASS::mvrnorm(N, mu, sigma)
df = tibble(rMZall = vs[,1], rDZall = vs[,2], n_twin_pairs = runif(N, 5000, 50000))
plot <- function(min_twin_pairs) {
ggplot(data=df |> filter(n_twin_pairs > min_twin_pairs), aes(rMZall, rDZall)) +
ggtitle(sprintf("Studies with > %d twin pairs", min_twin_pairs)) +
theme(legend.position="none") +
# Bounds
scale_x_continuous(name = "rMZ", limits = c(-0.05, 1.1), breaks = seq(0,1,0.25)) +
scale_y_continuous(name = "rDZ", limits = c(-0.05, 1), breaks = seq(0,1,0.25)) +
coord_fixed() +
# Scatterplot
stat_density2d(aes(fill=..level.., alpha=..level..), geom='polygon', colour='black', linewidth = 0.1) +
scale_fill_continuous(low="green", high="red") +
geom_point(aes(size = sqrt(n_twin_pairs))) +
scale_size_continuous(range = c(0, 1)) +
# AE and AD lines
geom_abline(intercept = 0, slope = .5) +
annotate(geom = "richtext", x = 1, y = .5, label = "AE model", angle = 26.6) +
geom_abline(intercept = 0, slope = .25) +
annotate(geom = "richtext", x = 1, y = .25, label = "AD model", angle = 14.0)
}
plot1000 = plot(min_twin_pairs = 1000)
plot4000 = plot(min_twin_pairs = 4000)
plot1000
plot4000
plot1000 + plot4000
您可以改用geomtextpath,特别是
geomtextpath::geom_labelabline()
。它会自动处理定位,因此您无需摆弄角度、画布大小等。