我的目标是制作一个组合图,将散点图和两个密度估计图结合在一起。我面临的问题是,由于密度图缺少轴标签和散点图的图例,密度图与散点图没有正确对齐。可以通过调整
plot.margin
来解决,但这不是一个理想的解决方案,因为如果对绘图进行更改,就需要一遍又一遍地进行调整。有没有一种方法可以使所有绘图区域完美对齐?
我尽可能保持代码的简洁,但为了重现问题,仍然有相当多的代码。
library(ggplot2)
library(gridExtra)
df <- data.frame(y = c(rnorm(50, 1, 1), rnorm(50, -1, 1)),
x = c(rnorm(50, 1, 1), rnorm(50, -1, 1)),
group = factor(c(rep(0, 50), rep(1,50))))
empty <- ggplot() +
geom_point(aes(1,1), colour="white") +
theme(
plot.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.ticks = element_blank()
)
scatter <- ggplot(df, aes(x = x, y = y, color = group)) +
geom_point() +
theme(legend.position = "bottom")
top_plot <- ggplot(df, aes(x = y)) +
geom_density(alpha=.5, mapping = aes(fill = group)) +
theme(legend.position = "none") +
theme(axis.title.y = element_blank(),
axis.title.x = element_blank(),
axis.text.y=element_blank(),
axis.text.x=element_blank(),
axis.ticks=element_blank() )
right_plot <- ggplot(df, aes(x = x)) +
geom_density(alpha=.5, mapping = aes(fill = group)) +
coord_flip() + theme(legend.position = "none") +
theme(axis.title.y = element_blank(),
axis.title.x = element_blank(),
axis.text.y = element_blank(),
axis.text.x=element_blank(),
axis.ticks=element_blank())
grid.arrange(top_plot, empty, scatter, right_plot, ncol=2, nrow=2, widths=c(4, 1), heights=c(1, 4))
set.seed()
函数,以确保输出结果可复现。 - Chris