Home > Article > Backend Development > 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:
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!