我尝试使用ggplot创建一个包含单个图例的多面板图。我已经能够通过使用以下代码创建我的六个单独的图来创建多面板图:
p1 <- ggplot(data, aes(y = value, x = Time))+
geom_point(position="dodge")+geom_line(aes(group=group,linetype=group))
我在另外五个图中使用了类似的代码。我在&#39;网格中使用了pushViewport函数。库创建一个mutlipanel图:
pushViewport(viewport(layout = grid.layout(2, 3)))
print(p1,vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
print(p2,vp = viewport(layout.pos.row = 1, layout.pos.col = 2))
print(p3,vp = viewport(layout.pos.row = 1, layout.pos.col = 3))
print(p4,vp = viewport(layout.pos.row = 2, layout.pos.col = 1))
print(p5,vp = viewport(layout.pos.row = 2, layout.pos.col = 2))
print(p6,vp = viewport(layout.pos.row = 2, layout.pos.col = 3))
我现在想做的但似乎无法弄清楚是为所有六个地块添加一个传奇。我已经阅读了一些关于在绘图边界之外添加图例的内容,但似乎无法将此工具与pushViewport方法一起使用。
答案 0 :(得分:0)
以下将使用主题显示左上角的单个图例(legend.justification ='left',legend.position = c(0,0.75))
library(grid)
数据示例
x<-c(1,1,2,2)
y<-c(107, 110, 110, 118)
data<-data.frame(x,y)
data$group<-as.factor(c(1,2,1,2))
Ggplot
p1 <- ggplot(data, aes(y = y, x = x)) + geom_point(position="dodge") + geom_line(aes(group=group,linetype=group)) + theme(legend.justification = 'left', legend.position=c(0,0.75))
p2 <- ggplot(data, aes(y = y, x = x)) + geom_point(position="dodge") + geom_line(aes(group=group,linetype=group)) + theme(legend.position = "none")
p3 <- ggplot(data, aes(y = y, x = x)) + geom_point(position="dodge") + geom_line(aes(group=group,linetype=group)) + theme(legend.position = "none")
p4 <- ggplot(data, aes(y = y, x = x)) + geom_point(position="dodge") + geom_line(aes(group=group,linetype=group)) + theme(legend.position = "none")
p5 <- ggplot(data, aes(y = y, x = x)) + geom_point(position="dodge") + geom_line(aes(group=group,linetype=group)) + theme(legend.position = "none")
p6 <- ggplot(data, aes(y = y, x = x)) + geom_point(position="dodge") + geom_line(aes(group=group,linetype=group)) + theme(legend.position = "none")
pushViewport(viewport(layout = grid.layout(3, 2)))
print(p1,vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
print(p2,vp = viewport(layout.pos.row = 1, layout.pos.col = 2))
print(p3,vp = viewport(layout.pos.row = 2, layout.pos.col = 1))
print(p4,vp = viewport(layout.pos.row = 2, layout.pos.col = 2))
print(p5,vp = viewport(layout.pos.row = 3, layout.pos.col = 1))
print(p6,vp = viewport(layout.pos.row = 3, layout.pos.col = 2))