我想知道是否有办法让一个共同的传奇和同时为多面板图绘制相同的绘图宽度。我知道如何在没有图例的情况下获得相同的绘图宽度,或者使用不垂直居中的图例。
这是哈德利用于常见传奇(https://github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs)的修复:
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个图表以相同的绘图宽度和常见的垂直居中图例进行图形显示。
答案 0 :(得分:0)
我认为你可以通过分面更好地实现目标:
ggplot(dsamp, aes(x = carat, y = price, colour = clarity)) +
geom_point(data = cbind(dsamp, group = 1)) +
geom_path(data = cbind(dsamp, group = 2)) +
facet_grid(group ~ .) +
theme(strip.text.y = element_blank(),
strip.background = element_blank()) +
ggtitle("this is a title")
我假设您的图中的变量与示例中的变量相同。否则,当我需要自己对齐绘图时,我不得不使用大量的修改:请参阅scatterplot with alpha transparent histograms in R以获取示例。