Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save plot and legend to separate files?

Tags:

r

ggplot2

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?

like image 424
Katrin Leinweber Avatar asked Jan 08 '15 15:01

Katrin Leinweber


People also ask

How do you save a plot in Python?

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.

How do I plot only legends in R?

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().


2 Answers

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.

like image 139
Roland Avatar answered Oct 04 '22 14:10

Roland


This is possible with cowplot and ggpubr.

library(cowplot)
my_legend <- get_legend(your_ggplot_object)
library(ggpubr)
as_ggplot(my_legend)
like image 36
derelict Avatar answered Oct 04 '22 13:10

derelict