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()
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()
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.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Besides that, you could read some of the other articles of my homepage. I have released numerous tutorials already.
- Remove Legend in ggplot2
- Change Legend Title in ggplot2
- Remove Legend Title from ggplot2 Plot
- Change Display Order of ggplot2 Plot Legend
- Show ggplot2 Legend at the Bottom of a Plot & Horizontally Aligned
- Add Common Legend to Combined ggplot2 Plots
- Control Size of ggplot2 Legend Items
- R Graphics Gallery
- The R Programming Language
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.
Statistics Globe Newsletter
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.)
Hey Hans,
Thank you for the very interesting question. In fact, it inspired me to write a new tutorial about this topic: https://statisticsglobe.com/divide-legend-of-ggplot2-plot-in-r
I hope this helps!
Joachim
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!
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
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! 🙂
Hello Saskia,
I understand that you want to show the pattern and the color on the legend in a combined way. Maybe you can do it easily, like in the examples of the ggpatern R package tutorial. If it doesn’t help, you can post your question to our Facebook discussion group: https://www.facebook.com/groups/statisticsglobe.
Regards,
Cansu