How to Create a Single Legend for Multiple Subplots in Matplotlib?

Susan Sarandon
Release: 2024-11-03 20:17:29
Original
168 people have browsed it

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>
Copy after login

Here:

  • ax represents the last axis in the subplot grid.
  • handles is a list of handles (lines, markers, etc.) representing the legend entries.
  • labels is a corresponding list of labels for the legend entries.
  • loc specifies the location of the legend within the figure (e.g., 'upper center' for above the plots).

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>
Copy after login

Additional Considerations

  • To remove legends from individual subplots, refer to "Remove the legend on a matplotlib figure" for guidance.
  • For merging twiny legends, consult "Secondary axis with twinx(): how to add to legend" for more information.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!