Home >Backend Development >Python Tutorial >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:
import matplotlib.patches as mpatches import matplotlib.pyplot as plt red_patch = mpatches.Patch(color='red', label='The red data')
<code class="python">plt.legend(handles=[red_patch])</code>
Example Image:
[Image of legend with a red patch labeled "The red data"]
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!