How to plot just the legends in ggplot2?

Solution 1:

Here are 2 approaches:

Set Up Plot

library(ggplot2) 
library(grid)
library(gridExtra) 

my_hist <- ggplot(diamonds, aes(clarity, fill = cut)) + 
    geom_bar() 

Cowplot approach

# Using the cowplot package
legend <- cowplot::get_legend(my_hist)

grid.newpage()
grid.draw(legend)

Home grown approach

Shamelessly stolen from: Inserting a table under the legend in a ggplot2 histogram

## Function to extract legend
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]] 
    legend
} 

legend <- g_legend(my_hist) 

grid.newpage()
grid.draw(legend) 

Created on 2018-05-31 by the reprex package (v0.2.0).

Solution 2:

Cowplot handily adds a function to extract the legend. The following is taken directly from the manual.

library(ggplot2)
library(cowplot)
p1 <- ggplot(mtcars, aes(mpg, disp)) + geom_line()
plot.mpg <- ggplot(mpg, aes(x = cty, y = hwy, colour = factor(cyl))) + geom_point(size=2.5)

# Note that these cannot be aligned vertically due to the legend in the plot.mpg
ggdraw(plot_grid(p1, plot.mpg, ncol=1, align='v'))

# now extract the legend
legend <- get_legend(plot.mpg)

# and replot suppressing the legend
plot.mpg <- plot.mpg + theme(legend.position='none')

# Now plots are aligned vertically with the legend to the right
ggdraw(plot_grid(plot_grid(p1, plot.mpg, ncol=1, align='v'),
                 plot_grid(NULL, legend, ncol=1),
                 rel_widths=c(1, 0.2)))

Solution 3:

I used the ggpubr package - makes it very easy!

https://rpkgs.datanovia.com/ggpubr/reference/get_legend.html

# Extract the legend. Returns a gtable
leg <- get_legend(p)

# Convert to a ggplot and print
as_ggplot(leg)