Creating legends for plots is an essential part of data visualization. Legends help to convey information about the visual representation of data.

In Matplotlib, legends can be added to individual subplots or to the entire figure. Some of the most commonly used methods to add legends to Matplotlib figures are the figure.legend method and the handles and labels property.

These methods can be used to add a single legend to multiple subplots or when the line handles and lines are different. Single Legend for All Subplots With figure.legend Method in Matplotlib

When creating plots with multiple subplots in Matplotlib, it can be tricky to add legends to each plot individually.

However, the figure.legend method provides an easy solution to this problem. With this method, you can get a legend at the figure level, which will apply to all subplots simultaneously.

To use the figure.legend method, you need to first create and plot data in the subplots. Once the subplots are created, you can use the legend call on the instance of the figure object.

For example, consider a scenario where you have created two subplots and want to add a single legend to both subplots. “`

import matplotlib.pyplot as plt

## import numpy as np

fig, axs = plt.subplots(2)

x = np.linspace(-np.pi, np.pi, 100)

y1 = np.sin(x)

y2 = np.cos(x)

axs[0].plot(x, y1, label=’sin’)

axs[1].plot(x, y2, label=’cos’)

fig.legend(loc=’upper right’)

plt.show()

“`

In the above example, the `figure.legend` method adds a single legend at the figure level with the location specified as `upper right`. This will be applied to both subplots.

## Using handles and labels of the last Axes

Another approach to creating a single legend for all subplots in Matplotlib is using handles and labels. In this method, you need to manually provide the handles and labels of the plot lines to create a legend.

For example, let’s say you have created three subplots and want to add a single legend to all three subplots. “`

import matplotlib.pyplot as plt

## import numpy as np

fig, axs = plt.subplots(3)

x = np.linspace(-np.pi, np.pi, 100)

y1 = np.sin(x)

y2 = np.cos(x)

y3 = np.tan(x)

axs[0].plot(x, y1)

axs[1].plot(x, y2)

axs[2].plot(x, y3)

handles, labels = axs[-1].get_legend_handles_labels()

fig.legend(handles, labels, loc=’upper right’)

plt.show()

“`

In this example, `handles` and `labels` are obtained from the last Axes using the `get_legend_handles_labels()` method. Subsequently, these are used to pass as parameters to the `fig.legend()` method.

The `loc` parameter specifies the location of the legend box. Single Legend for All Subplots With figure.legend Method When Line Handles and Lines Are Different in Matplotlib

If you have different line patterns and labels in different subplots, the previous method will not work.

In this case, you will need to use a combination of methods.

## Getting all line handles and labels from all subplots

Suppose you have a scenario where you have two subplots with different line styles and want to create a single legend for both. “`

import matplotlib.pyplot as plt

## import numpy as np

fig, axs = plt.subplots(2)

x = np.linspace(-np.pi, np.pi, 100)

y1 = np.sin(x)

y2 = np.cos(x)

axs[0].plot(x, y1, ‘–‘, label=’sin’)

axs[1].plot(x, y2, ‘-‘, label=’cos’)

plt.show()

“`

In this example, there are different line styles in each subplot. In order to create a single legend, we need to extract all the handles and labels from the subplots.

“`

import matplotlib.pyplot as plt

## import numpy as np

fig, axs = plt.subplots(2)

x = np.linspace(-np.pi, np.pi, 100)

y1 = np.sin(x)

y2 = np.cos(x)

axs[0].plot(x, y1, ‘–‘, label=’sin’)

axs[1].plot(x, y2, ‘-‘, label=’cos’)

lines = []

labels = []

## for ax in axs:

handles, this_labels = ax.get_legend_handles_labels()

lines.extend(handles)

labels.extend(this_labels)

fig.legend(lines, labels, loc=’upper right’)

plt.show()

“`

Here, we extract the `handles` and `labels` for each subplot using a for loop. We then use the `extend` method to add the handles and labels to two separate lists.

Finally, we pass these lists to the `fig.legend()` method to create a single legend.

## Using list extend method for more lines and labels

If you have more lines and labels, you can create a list of handles and labels manually using the `Line2D` class in Matplotlib. “`

import matplotlib.lines as mlines

import matplotlib.pyplot as plt

## import numpy as np

fig, axs = plt.subplots(2)

x = np.linspace(-np.pi, np.pi, 100)

y1 = np.sin(x)

y2 = np.cos(x)

y3 = np.tan(x)

cos_handle = mlines.Line2D([], [], linestyle=’-‘, color=’black’, label=’cos’)

sin_handle = mlines.Line2D([], [], linestyle=’–‘, color=’black’, label=’sin’)

tan_handle = mlines.Line2D([], [], linestyle=’-.’, color=’black’, label=’tan’)

axs[0].plot(x, y1, ‘–‘, label=’sin’)

axs[1].plot(x, y2, ‘-‘, label=’cos’)

axs[1].plot(x, y3, ‘-.’, label=’tan’)

handles = [sin_handle, cos_handle, tan_handle]

labels = [h.get_label() for h in handles]

fig.legend(handles, labels, loc=’upper right’)

plt.show()

“`

In this example, we create three line objects using the `Line2D` class. We then use these objects to create a legend manually using the `handles` and `labels` lists in the `fig.legend()` method.

The `get_label()` method is used to extract the label for each line.

## Conclusion

Matplotlib provides several methods to create legends for plots. These include the `figure.legend` method and using handles and labels.

The former method is used when you want to create a single legend for all subplots in a figure. The latter method is used when you have different line patterns and labels in different subplots.

In both methods, you can manually create a list of handles and labels to pass as parameters to the `fig.legend()` method to create a customized legend. Matplotlib is a popular data visualization library in Python that provides a wide range of tools to create visualizations.

Legends are an essential part of plots, and they help convey information about the data represented in the plot. In Matplotlib, there are several ways to create legends for plots.

Two methods are commonly used for creating a single legend for multiple subplots – the figure.legend method and the handles and labels property. Using figure.legend method for a single legend in multiple subplots

The figure.legend method is used to create a single legend for multiple subplots.

It adds a legend at the figure level, which applies to all subplots simultaneously. The figure.legend method is straightforward to use.

Once you have created and plotted data in the subplots, you can call the legend method on the instance of the figure object to add a legend to all subplots. Let’s consider an example where we have two subplots, and we want to add a legend to both subplots.

“`

import matplotlib.pyplot as plt

## import numpy as np

fig, axs = plt.subplots(2)

x = np.linspace(-np.pi, np.pi, 100)

y1 = np.sin(x)

y2 = np.cos(x)

axs[0].plot(x, y1, label=’Sin Function’)

axs[1].plot(x, y2, label=’Cos Function’)

fig.legend(loc=’upper right’)

plt.show()

“`

In this example, we have created two subplots and plotted the Sine and Cosine functions in them. The `fig.legend()` method adds a legend with the location specified as `upper right`, which will apply to both subplots.

The `loc` parameter specifies the location of the legend box. The location of the legend can be set to any one of the following values:

* upper right – right aligned and top-aligned

* upper left – left aligned and top-aligned

* lower right – right aligned and bottom-aligned

* lower left – left aligned and bottom-aligned

* right – right aligned and vertically centered

* center left – left aligned and vertically centered

* center right – right aligned and vertically centered

* lower center – horizontally centered and bottom-aligned

* upper center – horizontally centered and top-aligned

* center – horizontally and vertically centered

## Using handles and labels property for a single legend in multiple subplots

The handles and labels property can also be used to create a single legend for multiple subplots. In this method, you manually provide the handles and labels of the plot lines to create a legend.

The handles and labels are extracted from each subplot using the `get_legend_handles_labels()` method. Once you have obtained the handles and labels for all subplots, you can pass them as parameters to the `fig.legend()` method.

Let’s consider a scenario where we have three subplots with different line styles, and we want to create a single legend for all of them. “`

import matplotlib.pyplot as plt

## import numpy as np

fig, axs = plt.subplots(3)

x = np.linspace(-np.pi, np.pi, 100)

y1 = np.sin(x)

y2 = np.cos(x)

y3 = np.tan(x)

axs[0].plot(x, y1, ‘–‘, label=’Sin Function’)

axs[1].plot(x, y2, ‘-‘, label=’Cos Function’)

axs[2].plot(x, y3, ‘-.’, label=’Tan Function’)

handles = []

labels = []

## for ax in axs:

h, l = ax.get_legend_handles_labels()

handles.extend(h)

labels.extend(l)

fig.legend(handles, labels, loc=’upper right’)

plt.show()

“`

In this example, we have created three subplots with different line styles and plotted the Sine, Cosine, and Tangent functions. The `handles` and `labels` are extracted from each subplot using a for loop.

The `extend()` method is used to add the handles and labels to separate lists. Finally, we pass these lists to the `fig.legend()` method to create a single legend for all subplots.

## Final Thoughts

In summary, legends are an essential part of data visualization. They provide valuable information about the plotted data.

Matplotlib provides several methods to create legends for plots. Two commonly used methods for creating single legends for multiple subplots are the figure.legend method and the handles and labels property.

The figure.legend method adds a legend at the figure level that applies to all subplots, whereas the handles and labels property allows you to manually provide the handles and labels of the plot lines to create a legend. With these methods, you can create customized legends that convey the information you need to present in a clear and concise manner.

In this article, we explored the methods used in Matplotlib to create a single legend for multiple subplots. The first technique is by using the figure.legend method which adds a legend at the figure level, applying to all subplots.

The second method is by using the handles and labels property, which allows you to extract handles and labels from each subplot and pass them to the fig.legend() method. These methods provide flexibility to the user, and one can customize the legend to suit their needs.

It is crucial to remember that legends aid in the interpretation of plotted data. So, creating them with care and clarity is a crucial component of data visualization.