Home  >  Article  >  Backend Development  >  How to Create a Custom Legend in Matplotlib Using Patches?

How to Create a Custom Legend in Matplotlib Using Patches?

Linda Hamilton
Linda HamiltonOriginal
2024-10-22 15:17:03512browse

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>

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>

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!

Statement:
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