Reputation: 6314
I'm trying to generate a ggplot
which shares the legend from a list of ggplots
.
Here's my code:
#generate the list of plots:
set.seed(1)
plot.list <- vector(mode="list",2)
plot.list[[1]] <- ggplot(data.frame(group=rep(LETTERS[1:3],10),val=rnorm(30)),aes(val,color=group))+geom_density(adjust=1)+theme_minimal()
set.seed(10)
plot.list[[2]] <- ggplot(data.frame(group=rep(LETTERS[1:3],10),val=rnorm(30)),aes(val,color=group))+geom_density(adjust=1)+theme_minimal()
So:
plot.list[[1]]
and,
plot.list[[2]]
Now, to make a single plot that shares their legend:
g <- ggplotGrob(plot.list[[1]]+theme_minimal()+theme(legend.position="right"))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
plot(legend)
lheight <- sum(legend$height)
lwidth <- sum(legend$width)
gl <- lapply(plot.list,function(x) x+theme_minimal()+theme(legend.position="none"))
gl <- c(gl,nrow=1,ncol=2)
combined <- switch(position,"bottom"=arrangeGrob(do.call(arrangeGrob,gl),
legend,
ncol=1,
heights = unit.c(unit(1, "npc") - lheight, lheight)),
"right" = arrangeGrob(do.call(arrangeGrob,gl),
legend,
ncol=2,
widths=unit.c(unit(1,"npc")-lwidth,lwidth)))
But that (plot(combined)
) generates a plot with the gray background:
How can I get the combined
plot have the same background as the individual plots?
Upvotes: 1
Views: 154
Reputation: 4307
Perhaps you would be better off combining the data frames and using facet_wrap()
?
set.seed(1)
df1<-data.frame(group=rep(LETTERS[1:3],10),val=rnorm(30),dfz=1)
set.seed(10)
df2<-data.frame(group=rep(LETTERS[1:3],10),val=rnorm(30),dfz=2)
df<-rbind(df1,df2)#combine dataframes
ggplot(df,aes(val,color=group))+geom_density(adjust=1)+theme_minimal()+
facet_wrap(~dfz,scales='free') #facet_wrap by distinguishing column
Upvotes: 1