【发布时间】:2016-12-02 21:33:59
【问题描述】:
我的目标是一个复合图,它结合了一个散点图和 2 个密度估计图。我面临的问题是由于缺少密度图的轴标记和散点图的图例,密度图与散点图没有正确对齐。可以通过使用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))
【问题讨论】:
-
仅供参考,您应该在 R 中采样的示例之前
set.seed(),以便输出可重现 -
@Chris:实际数据在这里并不重要。所以我觉得没关系。
-
@user20650:感谢您的链接。我正在玩它,但还不能让它工作。但我认为这是要走的路。