Home > Article > Backend Development > How to Create a Single Legend for Multiple Subplots in Matplotlib?
Creating a Single Legend for Multiple Subplots in Matplotlib
In Matplotlib, creating multiple subplots side by side enables the visualization of different datasets or aspects of a single data set in a single figure. However, when these subplots have similar legends, displaying multiple legends can be unnecessary and visually cluttered. Fortunately, Matplotlib offers a solution to consolidate legends into a single, cohesive representation.
Solution: Using get_legend_handles_labels()
To create a single legend for multiple subplots, utilize the get_legend_handles_labels() function on the last axis. This function collects the necessary information from label= arguments, allowing you to manually create a consolidated legend.
<code class="python">handles, labels = ax.get_legend_handles_labels() fig.legend(handles, labels, loc='upper center')</code>
Here:
If you're using the pyplot interface instead of the Axes interface, employ this code:
<code class="python">handles, labels = plt.gca().get_legend_handles_labels()</code>
Additional Considerations
The above is the detailed content of How to Create a Single Legend for Multiple Subplots in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!