Home > Article > Backend Development > How to Create and Add Multiple Custom Legend Items in Matplotlib?
Automated Legend Handling vs. Manual Legend Creation
When working with matplotlib, it's often desirable to manuellly add legend items that consist of a color and a label. However, manually adding multiple legend items can be cumbersome and lead to duplicates.
The approach described by the user, ax2.legend(self.labels,colorList[:len(self.labels)]), does not appear to function as expected because matplotlib offers a more elegant solution for manually creating legend items.
Creating Custom Legend Items
As suggested by the Legend Guide, we can use the Patches class to define custom legend items. A patch is a rectangular area that can be specified with a color and a label. For instance:
<code class="python">import matplotlib.patches as mpatches red_patch = mpatches.Patch(color='red', label='The red data')</code>
This creates a legend patch with a red rectangular area and the label "The red data".
Adding Multiple Legend Items
To add multiple patches to the legend, we can use the plt.legend function and pass a list of patches as the handles argument. For example:
<code class="python">blue_patch = mpatches.Patch(color='blue', label='The blue data') plt.legend(handles=[red_patch, blue_patch])</code>
This will result in a legend with two entries, one for the red data and one for the blue data.
By utilizing this approach, you can manually create and control the contents of your legend, even when dealing with a large number of items.
The above is the detailed content of How to Create and Add Multiple Custom Legend Items in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!