Combine Multiple ggplot2 Legends in R (Example)

 

In this R tutorial you’ll learn how to create only a single ggplot2 legend.

The post looks as follows:

It’s time to dive into the R syntax:

 

Example Data, Packages & Default Plot

Consider the following example data:

data <- data.frame(x = 1:5,                              # Create data
                   y = 1:5,
                   shape = letters[1:5],
                   color = letters[1:5])
data
#   x y shape color
# 1 1 1     a     a
# 2 2 2     b     b
# 3 3 3     c     c
# 4 4 4     d     d
# 5 5 5     e     e

As you can see based on the previous output of the RStudio console, the example data consists of four columns.

The variables x and y contain some numeric values, the shape variable contains different shaping levels, and the color variable contains different levels for the colors of the plot.

In this tutorial, we’ll also need to install and load the ggplot2 package:

install.packages("ggplot2")                              # Install ggplot2 package
library("ggplot2")                                       # Load ggplot2 package

As next step, we can plot our data:

ggplot(data, aes(x, y, shape = shape, color = color)) +  # Create ggplot
  geom_point()

 

r graph figure 1 combine multiple ggplot2 legends r

 

The output of the previous R programming code is shown in Figure 1. As you can see, our plot contains two legends – One for the shape and another one for the color of the data points.

So what went wrong? How can we remove one of those legends? That’s what I’m going to show next.

 

Example: Harmonizing Legend with shape & color Arguments

This Example explains how to draw only a single legend to a ggplot2 plot in R. If we want to get rid of duplicated legends, we have to define the same variable for the shape and color arguments. For instance, we could use the shape variable of our example data frame for both – shape and color:

ggplot(data, aes(x, y, shape = shape, color = shape)) +  # shape = color
  geom_point()

 

r graph figure 2 combine multiple ggplot2 legends r

 

The output of the previous R programming syntax is shown in Figure 2: As you can see the two legends were merged into one single legend.

 

Video, Further Resources & Summary

I have recently published a video instruction on my YouTube channel, which illustrates the R programming syntax of this tutorial. You can find the video instruction below:

 

The YouTube video will be added soon.

 

Besides that, you could read some of the other articles of my homepage. I have released numerous tutorials already.

 

To summarize: This tutorial illustrated how to combine multiple ggplot2 legends in the R programming language. In case you have any further questions, tell me about it in the comments section below.

 



Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top