Home > Backend Development > Python Tutorial > How to Manually Add Legends in Matplotlib with Distinct Colors and Labels?

How to Manually Add Legends in Matplotlib with Distinct Colors and Labels?

Susan Sarandon
Release: 2024-10-22 15:09:03
Original
613 people have browsed it

How to Manually Add Legends in Matplotlib with Distinct Colors and Labels?

Manually Creating a Legend in Matplotlib

When working with large datasets in matplotlib, manually adding items to the legend with distinct colors and labels can be a useful technique. This prevents duplicates that can arise from automatically including data to the plot.

Original Approach

The original approach attempted to use the following code:

ax2.legend(self.labels, colorList[:len(self.labels)])
plt.legend()
Copy after login

where self.labels is the number of desired legend labels, and colorList is a subset of the colors used in the plot. However, this method yielded no entries in the legend.

Solution

To manually create a legend, the Legend Guide in matplotlib documentation provides a solution. It involves creating a special artist, called a Patch, which can be used as a handle in the legend.

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

# Create a red patch
red_patch = mpatches.Patch(color='red', label='The red data')
Copy after login

This patch now represents the red data and can be directly added to the legend.

plt.legend(handles=[red_patch])
Copy after login

Adding Multiple Patches

To add multiple colors and labels, the same technique can be applied by creating additional patches.

blue_patch = mpatches.Patch(color='blue', label='The blue data')
plt.legend(handles=[red_patch, blue_patch])
Copy after login

This will result in a legend with two entries, one for each patch.

The above is the detailed content of How to Manually Add Legends in Matplotlib with Distinct Colors and Labels?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template