Placing Two Different Legends on the Same Graph With Matplotlib
Last Updated :
17 Jul, 2024
Creating informative and visually appealing graphs is a crucial aspect of data visualization. In many cases, a single legend is insufficient to convey all the necessary information, especially when dealing with complex datasets. This article will guide you through the process of placing two different legends on the same graph using Python's Matplotlib library. By the end of this tutorial, you will be able to enhance your graphs by providing clear and distinct legends for different data representations.
Prerequisites
Before we start, ensure you have the following prerequisites:
- Basic knowledge of Python programming.
- Installed Python environment (Python 3.6 or higher).
- Installed matplotlib library. You can install it using the following command:
pip install matplotlib
Creating a Basic Plot Using Matplotlib
Let's start by creating a basic plot with two sets of data. We'll use matplotlib for this purpose.
Python
import matplotlib.pyplot as plt
import numpy as np
# Generate sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# Create a basic plot
plt.plot(x, y1, label='Sine Wave')
plt.plot(x, y2, label='Cosine Wave')
plt.title('Basic Plot with Sine and Cosine Waves')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()
Output:
Created PlotThis code generates a basic plot with sine and cosine waves.
Creating Legends On Same Graph
We create two separate legends:
- First Legend (Parameters)
- Second Legend (Algorithms)
1. Adding the First Legend
To add the first legend, use the legend() function. By default, matplotlib adds a single legend containing all the labeled elements.
Python
# Create a basic plot with the first legend
plt.plot(x, y1, label='Sine Wave')
plt.plot(x, y2, label='Cosine Wave')
plt.title('Plot with First Legend')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.legend(loc='upper right') # Positioning the legend
plt.show()
Output:
Added first legendThis code adds a legend for both the sine and cosine waves and positions it in the upper right corner.
2. Adding the Second Legend
To add a second legend, we need to use the ax.legend() method to create the first legend, and then manually add a second legend using the plt.gca().add_artist() method.
Python
# Create a basic plot
fig, ax = plt.subplots()
line1, = ax.plot(x, y1, label='Sine Wave')
line2, = ax.plot(x, y2, label='Cosine Wave')
# Add the first legend
first_legend = ax.legend(handles=[line1], loc='upper right')
# Add the second legend
second_legend = plt.legend(handles=[line2], loc='lower right')
# Manually add the first legend back to the plot
ax.add_artist(first_legend)
plt.title('Plot with Two Legends')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()
Output:
Added Second LegendThis code adds two separate legends to the plot, each representing one of the waveforms.
Customizing the Legends Same Graph
You can further customize the legends to enhance the visualization. For example, you can change the font size, background color, and border properties.
This code customizes the legends by adjusting the font size, adding a shadow, and modifying the border padding.
Python
# Create a basic plot
fig, ax = plt.subplots()
line1, = ax.plot(x, y1, label='Sine Wave')
line2, = ax.plot(x, y2, label='Cosine Wave')
# Add the first legend with customizations
first_legend = ax.legend(handles=[line1], loc='upper right', fontsize='small', frameon=True, shadow=True, borderpad=1)
# Add the second legend with customizations
second_legend = plt.legend(handles=[line2], loc='lower right', fontsize='small', frameon=True, shadow=True, borderpad=1)
# Manually add the first legend back to the plot
ax.add_artist(first_legend)
plt.title('Plot with Customized Legends')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()
Output:
Customized PlotHandling Legend Overlap
In some cases, the legends might overlap with the plot. To avoid this, you can adjust the position of the plot using ax.set_position()
:
Python
import matplotlib.pyplot as plt
import numpy as np
# Sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
fig, ax = plt.subplots()
ax.plot(x, y1, label='Sine')
ax.plot(x, y2, label='Cosine')
# Place legend outside the plot
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
# Adjust the position of the plot to make room for the legend
# This setting moves the plot leftwards, reducing its width
ax.set_position([0.1, 0.1, 0.6, 0.8]) # [left, bottom, width, height]
plt.show()
Output:
Handling Legend OverlapBest Practices for Multiple Legends
When working with multiple legends, it is essential to follow best practices to ensure clarity and readability:
- Positioning: Place legends in a way that minimizes overlap with the data and other graphical elements. Common positions include the upper right, upper left, or outside the plot area.
- Titles: Use distinct titles for each legend to clearly indicate the subset of data it corresponds to.
- Colors and Styles: Use consistent colors and line styles within each legend to maintain visual coherence.
- Legend Size: Ensure that the legends are large enough to be readable but not so large that they overwhelm the graph.
Conclusion
Adding two different legends to the same graph can enhance the readability and interpretation of complex data visualizations. By following the steps outlined in this article, you can create a plot with two legends, customize them to suit your needs, and display or save the plot. With matplotlib, the process is straightforward and flexible, allowing you to produce clear and informative visualizations.
Similar Reads
How to set font size of Matplotlib axis Legend?
Prerequisite: Matplotlib In this article, we will see how to set the font size of matplotlib axis legend using Python. For this, we will use rcParams() methods to increase/decrease the font size. To use this we have to override the matplotlib.rcParams['legend.fontsize'] method. Syntax: matplotlib.rc
1 min read
Combining Two Boxplots With the Same Axes
Combining two boxplots with the same axes into one boxplot in Python is a common task in data visualization, especially when you want to compare distributions from different datasets or categories. This article will guide you through the process of creating combined boxplots using Python libraries s
3 min read
How to Change the Color of a Graph Plot in Matplotlib with Python?
Prerequisite: Matplotlib Python offers a wide range of libraries for plotting graphs and Matplotlib is one of them. Matplotlib is simple and easy to use a library that is used to create quality graphs. The pyplot library of matplotlib comprises commands and methods that makes matplotlib work like ma
2 min read
How to add a legend to a scatter plot in Matplotlib ?
In this article, we are going to add a legend to the depicted images using matplotlib module. We will use the matplotlib.pyplot.legend() method to describe and label the elements of the graph and distinguishing different plots from the same graph. Syntax: matplotlib.pyplot.legend( ["title_1", "Titl
2 min read
How to Place Legend Outside of the Plot in Matplotlib?
In this article, we will see how to put the legend outside the plot. Let's discuss some concepts : Matplotlib: Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with t
3 min read
How Change the vertical spacing between legend entries in Matplotlib?
Prerequisites: Matplotlib In this article, we will see how can we can change vertical space between labels of a legend in our graph using matplotlib, Here we will take two different examples to showcase our graph. Approach: Import required module.Create data.Change the vertical spacing between label
2 min read
How to Remove the Legend in Matplotlib?
Matplotlib is one of the most popular data visualization libraries present in Python. Using this matplotlib library, if we want to visualize more than a single variable, we might want to explain what each variable represents. For this purpose, there is a function called legend() present in matplotli
5 min read
How to Change the Line Width of a Graph Plot in Matplotlib with Python?
Prerequisite : Matplotlib In this article we will learn how to Change the Line Width of a Graph Plot in Matplotlib with Python. For that one must be familiar with the given concepts: Matplotlib : Matplotlib is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a
2 min read
Use different y-axes on the left and right of a Matplotlib plot
In this article, we are going to discuss how to create y-axes of both sides of a Matplotlib plot. Sometimes for quick data analysis, it is required to create a single graph having two data variables with different scales. For this purpose twin axes methods are used i.e. dual X or Y-axes. The matplot
2 min read
How to Add Markers to a Graph Plot in Matplotlib with Python?
In this article, we will learn how to add markers to a Graph Plot in Matplotlib with Python. For that just see some concepts that we will use in our work. Graph Plot: A plot is a graphical technique for representing a data set, usually as a graph showing the relationship between two or more variable
2 min read