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

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

Susan Sarandon
Susan SarandonOriginal
2024-11-03 20:17:29178browse

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:

  • 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>

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!

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