Open In App

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. 



Example:




# Load Package
library("ggplot2")
  
# Create a DataFrame 
data <- data.frame(
  Xdata = rnorm(10),                        
  Ydata = rnorm(10),
  LegendData = c("ld-01", "ld-02", "ld-03",
                 "ld-04", "ld-05", "ld-06",
                 "ld-07", "ld-08", "ld-09"
                 "ld-10"))
  
# Create a Scatter Plot and assign it 
# to gplot data object
gplot <- ggplot(data, aes(
  Xdata, Ydata, color = LegendData)) +   
  geom_point(size = 7)
gplot

Output:



Scatter Plot with legend

Packages Used:

Now, to draw only the legend of the plot without the plot, we have to load three packages named grid, gridExtra, and cowplot.

Syntax:

install.packages(“grid”) #For Install grid package

library(“grid”) #For Load grid package

Syntax:

install.packages(“gridExtra”) #For Install gridExtra package

library(“gridExtra”) #For Load gridExtra package

Syntax:

install.packages(“cowplot”) #For Install cowplot package

library(“cowplot”) #For Load cowplot package

Functions Used:

To draw only legend, we use three functions, which are from the above packages.

Syntax : get_legend(ggplot)

Parameter: A ggplot, from which to retrieve the legend

Return : Legend from plot

Syntax : grid.newpage()

Return : Erases current plot window and create a new plot window

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

Example:




# Load Packages
library("ggplot2")
library("grid")
library("gridExtra")
library("cowplot")
  
# Create a DataFrame
data <- data.frame(
  Xdata = rnorm(10), Ydata = rnorm(10),
  LegendData = c("ld-01", "ld-02", "ld-03",
                 "ld-04", "ld-05", "ld-06",
                 "ld-07", "ld-08", "ld-09"
                 "ld-10"))
  
# Create a Scatter Plot
gplot <- ggplot(data, aes(Xdata, Ydata, color = LegendData)) +   
  geom_point(size = 7)
  
# Draw Only Legend without plot
# Grab legend from gplot
legend <- get_legend(gplot)                    
  
# Create new plot window
grid.newpage()                              
  
# Draw Only legend 
grid.draw(legend) 

Output:

Only Legend Without Plot


Article Tags :