Home > Article > Backend Development > How to Create a Unified Legend for Multiple Subplots in Matplotlib?
In Matplotlib, when plotting data across multiple subplots, it can often be desirable to display a single legend for all plots. This is especially useful when the subplots share similar line styles, colors, or labels. By consolidating the legends, it helps to simplify the visualization and reduce clutter.
To achieve this, Matplotlib provides a convenient function called get_legend_handles_labels(). This function can be called on the last axis within the grid, and it collects all necessary legend information from the label= arguments used while plotting. The collected handles and labels can then be used to create a single legend for the entire figure.
For instance, if you have nine subplots arranged in a 3x3 grid, you can obtain the legend elements from the last subplot using the following code:
handles, labels = ax.get_legend_handles_labels()
where ax represents the last subplot axis in the grid. With the handles and labels collected, the legend can be created using fig.legend():
fig.legend(handles, labels, loc='upper center')
In this case, the legend will be positioned at the 'upper center' location within the figure. The loc= argument can be customized to place the legend anywhere within the figure.
Alternatively, if you're using thepyplot interface instead of theAxes interface, the following code can be used to retrieve legend handles and labels:
handles, labels = plt.gca().get_legend_handles_labels()
where plt.gca() returns the current axis object.
The above is the detailed content of How to Create a Unified Legend for Multiple Subplots in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!