【发布时间】:2014-11-28 22:46:09
【问题描述】:
我想知道是否有一种方法可以同时为多面板绘图提供相同的绘图宽度和。我知道如何在没有图例或没有垂直居中的图例的情况下获得相同的绘图宽度。
这是我用于常见图例 (https://github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs) 的 Hadley 修复:
library(ggplot2)
library(gridExtra)
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
p1 <- qplot(carat, price, data=dsamp, colour=clarity)
p2 <- qplot(carat, price, data=dsamp, colour=clarity, geom="path")
g_legend<-function(p){
tmp <- ggplotGrob(p)
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)}
legend <- g_legend(p1)
lwidth <- sum(legend$width)
## using grid.arrange for convenience
## could also manually push viewports
grid.arrange(arrangeGrob(p1 + theme(legend.position="none"),
p2 + theme(legend.position="none"),
main ="this is a title",
left = "This is my global Y-axis title"), legend,
widths=unit.c(unit(1, "npc") - lwidth, lwidth), nrow=1)
为了说明我的观点,我更改了p2,添加了同一数据集的另外两个变量,以保持与常见图例相同的清晰度:
p1 <- qplot(carat, price, data=dsamp, colour=clarity)
p2 <- qplot(depth, table, data=dsamp, colour=clarity, geom="path")
g_legend<-function(p){
tmp <- ggplotGrob(p)
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)}
legend <- g_legend(p1)
lwidth <- sum(legend$width)
## using grid.arrange for convenience
## could also manually push viewports
grid.arrange(arrangeGrob(p1 + theme(legend.position="none"),
p2 + theme(legend.position="none"),
main ="this is a title",
left = "This is my global Y-axis title"), legend,
widths=unit.c(unit(1, "npc") - lwidth, lwidth), nrow=1)
这在本例中可能没有意义,但我在同一个实验单元上有四个不同的测量值,我想以图形方式显示在 2 个具有相同绘图宽度和一个共同的垂直居中图例的绘图中。
【问题讨论】: