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

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

Creating a single legend for all subplots in a Matplotlib figure can be achieved by using a single legend for the entire figure, instead of individual legends for each subplot. Here's how you can do it:

  1. First, ensure each subplot uses a unique label for each plot.
  2. After creating all the subplots, use the fig.legend() method to create a single legend for the entire figure.

Here's an example:

import numpy as np import matplotlib.pyplot as plt # Generate some sample data x = np.linspace(0, 10, 100) y1 = np.sin(x) y2 = np.cos(x) fig, axs = plt.subplots(2, 1, figsize=(8, 6)) # Plot data on first subplot axs[0].plot(x, y1, label='sin(x)') axs[0].set_title('sin(x)') # Plot data on second subplot axs[1].plot(x, y2, label='cos(x)', color='orange') axs[1].set_title('cos(x)') # Create a single legend for the entire figure fig.legend(loc='upper right', bbox_to_anchor=(0.9, 0.95)) plt.tight_layout() plt.show() 

In the example above:

  • We have two subplots. The first one displays sin(x) and the second one displays cos(x).
  • After plotting the data on each subplot, we use fig.legend() to create a single legend for the entire figure. The bbox_to_anchor argument is used to position the legend on the figure. Adjust its values as needed to fit the legend properly on your figure.

More Tags

tableau-api ghostscript ag-grid-angular apache-tika getter reactive-programming verification socket.io abstract-class debian

More Programming Guides

Other Guides

More Programming Examples