How to Create a Unified Legend for Multiple Matplotlib Subplots?

Mary-Kate Olsen
Release: 2024-11-03 17:30:29
Original
701 people have browsed it

How to Create a Unified Legend for Multiple Matplotlib Subplots?

Creating a Unified Legend for Multiple Matplotlib Subplots

When using Matplotlib to visualize data in multiple subplots, it can be desirable to display a single comprehensive legend that applies to all subplots. Despite having different data values, the subplots may share the same line labels.

Solution:

The get_legend_handles_labels() function can be utilized to gather legend labels from all subplots:

<code class="python">handles, labels = ax.get_legend_handles_labels()</code>
Copy after login

Where ax represents the axis object of the final subplot in the grid.

To display the single legend, invoke:

<code class="python">fig.legend(handles, labels, loc='upper center')</code>
Copy after login

Pyplot Interface:

If employing the pyplot interface, retrieve legend elements with:

<code class="python">handles, labels = plt.gca().get_legend_handles_labels()</code>
Copy after login

Additional Notes:

  • For subplot legend removal, refer to "Remove the legend on a matplotlib figure."
  • To merge legends across subplots sharing the x-axis, consult "Secondary axis with twinx(): how to add to legend."

The above is the detailed content of How to Create a Unified Legend for Multiple Matplotlib Subplots?. 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!