How to Create a Custom Legend in Matplotlib Using Patches?

Linda Hamilton
Release: 2024-10-22 15:17:03
Original
452 people have browsed it

How to Create a Custom Legend in Matplotlib Using Patches?

Creating a Legend Manually in Matplotlib

Matplotlib offers the ability to add custom items to legends, enabling you to control their labels and colors. This is especially useful in situations where automatic legend creation results in duplicates.

To create a manual legend, you can utilize a specific artist class known as a Patch. Patches allow you to define shapes and colors that can be added to the legend. Here's an example:

<code class="python">import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

# Define a red patch with the label "Red data"
red_patch = mpatches.Patch(color="red", label="Red data")

# Add the patch to the legend
plt.legend(handles=[red_patch])

# Show the plot
plt.show()</code>
Copy after login

This code will display a legend with a single red entry labeled "Red data."

To add multiple patches to the legend, you can simply include them in the handles list passed to the plt.legend function. For example, to add a blue patch labeled "Blue data":

<code class="python"># Define a blue patch with the label "Blue data"
blue_patch = mpatches.Patch(color="blue", label="Blue data")

# Add both patches to the legend
plt.legend(handles=[red_patch, blue_patch])</code>
Copy after login

With this modification, your legend will now contain two entries: "Red data" and "Blue data."

The above is the detailed content of How to Create a Custom Legend in Matplotlib Using Patches?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!