我的目标是将散点图和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))
仅供参考,您应该'set.seed()',你中的R示例,使输出重复性 – Chris
@克里斯例子之前:实际数据在这里并不重要。所以我认为这并不重要。 – Alex
http://stackoverflow.com/questions/17370853/align-ggplot2-plots-vertically/17371177#17371177 – user20650