Home >Backend Development >Python Tutorial >How to Manually Create Custom Legend Entries in Matplotlib?

How to Manually Create Custom Legend Entries in Matplotlib?

Susan Sarandon
Susan SarandonOriginal
2024-10-22 22:12:02403browse

How to Manually Create Custom Legend Entries in Matplotlib?

Manual Legend Creation in Matplotlib

When dealing with complex plots, manually adding items to the legend becomes necessary to avoid duplicates. While trying to achieve this using a technique involving filtering a color list and adding items with ax2.legend() and .legend(), you encountered an unexpected outcome.

To manually create a legend entry, consider the following approach:

  1. Create a Patch: Import the matplotlib.patches module and create a Patch object. This object represents the visual element in the legend, such as a colored square. For example, to create a red patch labeled "The red data":
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

red_patch = mpatches.Patch(color='red', label='The red data')
  1. Add Patches to Legend: Use the .legend() function to add the patch to the legend. You can specify multiple patches to create a legend with multiple entries:
<code class="python">plt.legend(handles=[red_patch])</code>

Example Image:

[Image of legend with a red patch labeled "The red data"]

  1. Adding Multiple Patches: To add another patch, create a new Patch object and add it to the list of handles passed to .legend():
blue_patch = mpatches.Patch(color='blue', label='The blue data')

plt.legend(handles=[red_patch, blue_patch])

Example Image:

[Image of legend with two patches labeled "The red data" and "The blue data"]

By following these steps, you can manually add legend entries to your plots without relying on automatic generation, ensuring accuracy and customization.

The above is the detailed content of How to Manually Create Custom Legend Entries in Matplotlib?. 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