My question is closely related to R: Custom Legend for Multiple Layer ggplot , and to Format legend for multiple layers ggplot2 namely: I want to create custom legends for
The following is a hack. It extracts the legends from temporary plots and then combines everything using grid.arrange
.
g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)}
n <- 4; cols <- hcl(h=seq(15, 375-360/n, length=n)%%360, c=100, l=65)
cols1 <- cols[4:3]
names(cols1) <- c("positive", "non-positive")
plt_1 <- ggplot(data.one) +
geom_point(data=data.one,aes(x, y, color=lbl)) +
scale_color_manual(values=cols1)
cols2 <- cols[1:2]
names(cols2) <- c("high", "low")
plt_2 <- ggplot(data.one) +
geom_line(data=data.two, aes(x, y, color=classification)) +
scale_color_manual(values=cols2)
mylegend_1<-g_legend(plt_1)
mylegend_2<-g_legend(plt_2)
plt <- ggplot(data.one) +
geom_point(data=data.one,aes(x, y, color=lbl)) +
geom_line(data=data.two, aes(x, y, color=classification)) +
scale_color_discrete(guide="none")
library(gridExtra)
grid.arrange(plt,
arrangeGrob(mylegend_1, mylegend_2, nrow=6),
ncol=2,widths=c(7,1))
You'd need to fiddle a bit more to get the justification as in your expected output.