Draw ggplot2 Legend without Plot in R
A legend in the graph describes each part of the plot individually and is used to show statistical data in graphical form. In this article, we will see how to draw only the legend without a plot in ggplot2.
First, let us see how to draw a graph with a legend so that the difference is apparent. For that load the ggplot2 package by using library() function and create a DataFrame. To create an R plot, we use ggplot() function and for getting a scatter plot we add geom_point() function to ggplot() function.
Now, to draw only the legend of the plot without the plot, we have to load three packages named grid, gridExtra, and cowplot.
- grid package is used to produce a graphical output directly
install.packages(“grid”) #For Install grid package
library(“grid”) #For Load grid package
- gridExtra is an extension to grid package, it supports the creation and editing of graphic objects but with higher-level functions than grid.
install.packages(“gridExtra”) #For Install gridExtra package
library(“gridExtra”) #For Load gridExtra package
- cowplot package is used to enhance the presentability of figure by fixing its core components.
install.packages(“cowplot”) #For Install cowplot package
library(“cowplot”) #For Load cowplot package
To draw only legend, we use three functions, which are from the above packages.
- get_legend() function is used to hold the legend to a plot.
Syntax : get_legend(ggplot)
Parameter: A ggplot, from which to retrieve the legend
Return : Legend from plot
- grid.newpage() moves the grid to another device by removing it from the former device.
Syntax : grid.newpage()
Return : Erases current plot window and create a new plot window
- grid.draw() produces graphical output from a graphical object
Syntax : grid.draw(legend)
Return : Draw the legend to new plot window
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().