I have some datasets that contain more legend entries than can comfortably be distinguished with colors or at all displayed with symbols. It's effectively a rainbow, but across so many legend entries that they make the plots much higher than wide.
Since the legends are not really as important as comfortable sizing of the plot, I merely preview and remove them before saving the plots to PNGs.
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
However, having only the choice of either skewing the plot height or kicking the legend out completely, is a bit frustrating. A neat compromise would be to have the legend in a separate PNG, so it can be checked when really necessary. Is there a way to do this?
Saving a plot on your disk as an image file Now if you want to save matplotlib figures as image files programmatically, then all you need is matplotlib. pyplot. savefig() function. Simply pass the desired filename (and even location) and the figure will be stored on your disk.
Thus, in order to draw a plot with just legend, first, a legend is drawn and held to the plot using get_legend(), then the plot is erased using grid. newpage() and then the legend is drawn to a new plot window using grid. draw().
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 plot to different devices.
This is possible with cowplot
and ggpubr
.
library(cowplot)
my_legend <- get_legend(your_ggplot_object)
library(ggpubr)
as_ggplot(my_legend)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With