Home  >  Article  >  Backend Development  >  How to Create a Unified Legend for Multiple Matplotlib Subplots?

How to Create a Unified Legend for Multiple Matplotlib Subplots?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 17:30:29702browse

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>

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>

Pyplot Interface:

If employing the pyplot interface, retrieve legend elements with:

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

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!

Statement:
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