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

Have a look at the following video which I have published on my YouTube channel. In this tutorial, I give a detailed introduction to the ggplot2 Package and data visualization in R, structured in different sections with examples for beginners but also advanced users.

 

 

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.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


6 Comments. Leave new

  • Dear sir, I have two legends by purpose, but want one at the bottom and the other on the left hand side. How can I get to this? I only find code to move both legends together. (theme(legend.position= etc.)

    Reply
  • Hi Joachim,

    I’m trying to get your code to work, but I cannot seem to combine my legends. Can you help me, please?

    This is my code:

    ggplot(vrt.all,aes(x = int, y = value, color=factor(behaviour), linetype = factor(behaviour)))+
    geom_point(fill=”gray90″)+
    # Create interpolation line with geom_smooth (loess method is default with small nr observations,
    # see https://www.datanovia.com/en/blog/how-to-plot-a-smooth-line-using-ggplot2/)
    geom_smooth(method = “loess”)+
    labs(x=”Time interval (10 min)”, y=”Number of birds”,
    title=”Number of birds performing behaviours relative to baseline”)+
    scale_color_manual(name=”Behaviour”,
    labels=c(“Out of sight”, “Dust bathing”, “Drinking”, “Feeding”, “Foraging”, “Preening”, “Ïnattentive”, “Alert”),
    values=c(“#FFCC65″,”#FF6DB6″,”#490092″,”#006DDB”,”#D82632″,”#008600″,”#000000″,”#DB6D00″))+

    theme_bw()

    Thank you!

    Reply
    • Hi Saskia,

      I apologize for the delayed reply. I was on a long holiday, so unfortunately I wasn’t able to get back to you earlier. Do you still need help with your syntax?

      Regards,
      Joachim

      Reply
  • Hi Joachim,

    Now it’s my turn to apologize! I never got a notification of your reply, and now I accidentally ran into my own question here because I have exactly the same problem (but different dataset) again. This example might be a bit easier so please forget my original post and only focus on this one:

    library(ggplot2)
    library(ggpattern)

    ggplot(fbo.cont,aes(x = factor(inc.cond), y = freq.groundtubes, fill = factor(larv.cond))) +
    geom_boxplot_pattern(aes(fill = factor(larv.cond), pattern = factor(larv.cond)), colour=”black”) +
    theme_bw() +
    labs(x = “Incubation condition”, y = “Number of foraging bouts”, fill = “Larvae condition”,
    title = “Number of foraging bouts”) +
    scale_x_discrete(labels = c(“Dark”, “Light”)) +
    scale_pattern_manual(values=c(“stripe”, “wave”)) +
    scale_fill_manual(labels=c(“No larvae”,”Larvae”),
    values=c(“#009999”, “#cc9933″)) +
    stat_summary(fun=”mean”, position = position_dodge2(width = 0.75), shape = 4) +
    theme_bw()

    I have two conditions in a 2×2 factorial design (inc.cond and larv.cond). The larv.cond need to have both a color and pattern. I hope you can still help me! 🙂

    Reply

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.

Top