Manually Creating a Legend in Matplotlib
When working with large datasets in matplotlib, manually adding items to the legend with distinct colors and labels can be a useful technique. This prevents duplicates that can arise from automatically including data to the plot.
Original Approach
The original approach attempted to use the following code:
ax2.legend(self.labels, colorList[:len(self.labels)]) plt.legend()
where self.labels is the number of desired legend labels, and colorList is a subset of the colors used in the plot. However, this method yielded no entries in the legend.
Solution
To manually create a legend, the Legend Guide in matplotlib documentation provides a solution. It involves creating a special artist, called a Patch, which can be used as a handle in the legend.
import matplotlib.patches as mpatches import matplotlib.pyplot as plt # Create a red patch red_patch = mpatches.Patch(color='red', label='The red data')
This patch now represents the red data and can be directly added to the legend.
plt.legend(handles=[red_patch])
Adding Multiple Patches
To add multiple colors and labels, the same technique can be applied by creating additional patches.
blue_patch = mpatches.Patch(color='blue', label='The blue data') plt.legend(handles=[red_patch, blue_patch])
This will result in a legend with two entries, one for each patch.
The above is the detailed content of How to Manually Add Legends in Matplotlib with Distinct Colors and Labels?. For more information, please follow other related articles on the PHP Chinese website!