Save plot and legend to split files?
I have several datasets that contain more legend entries than can be conveniently distinguished by colors or displayed with symbols at all. It is effectively a rainbow, but across so many legend entries that they render the graphs much higher than wide.
Since the legends are not nearly as important as convenient plot calibration, I just go through and delete them before saving the graphics to PNG.
Like this:
library(ggplot2)
p <- ggplot(diamonds, aes(cut, depth)) + geom_point(aes(colour = factor(carat), size = price))
p
p <- p + theme(legend.position = "none")
p
Having only the choice to either distort the plot's height or kick out the legend entirely, however, is a little disappointing. The best compromise would be to have the legend in a separate PNG, so you can check it out when you really need it. Is there a way to do this?
+3
source to share
1 answer
library(ggplot2)
p <- ggplot(diamonds, aes(cut, depth)) + geom_point(aes(colour = factor(carat), size = price))
#extract legend
#https://github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs
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)
}
mylegend <- g_legend(p)
library(grid)
grid.draw(mylegend)
Just talk to different devices.
+3
source to share