Matplotlib Subplots Legend

Matplotlib Subplots Legend

Matplotlib is a popular Python library used for creating static, animated, and interactive visualizations in Python. It provides a wide range of plotting functions and options to customize your plots. One of the key features of Matplotlib is the ability to create multiple plots on a single figure using subplots.

Subplots allow you to divide the figure into multiple axes on a grid and plot different datasets or visualizations simultaneously. Each subplot can have its own set of axes and can be customized individually. In this article, we will explore how to add legends to subplots in Matplotlib.

What is a Legend?

A legend is a box that provides a visual representation of the elements present in a plot. It helps in identifying different data points or groups in a plot. Legends are crucial when multiple datasets or visualizations are present on a single plot or figure.

In Matplotlib, legends can be added to subplots to describe the elements present in each subplot. Each subplot can have its own legend, which can either be unique to the subplot or shared between multiple subplots.

Adding a Legend to a Subplot in Matplotlib

To add a legend to a subplot in Matplotlib, you can use the legend function provided by the Axes class. The legend function takes several parameters to customize the appearance and position of the legend.

Here is an example of adding a legend to a subplot:

import matplotlib.pyplot as plt

# Create a figure with subplots
fig, axs = plt.subplots(2, 2)

# Plot data on the subplots
axs[0, 0].plot([1, 2, 3], [1, 4, 9], 'ro', label='Data 1')
axs[0, 1].plot([1, 2, 3], [10, 20, 30], 'bo', label='Data 2')
axs[1, 0].plot([1, 2, 3], [5, 7, 11], 'go', label='Data 3')
axs[1, 1].plot([1, 2, 3], [2, 4, 6], 'yo', label='Data 4')

# Add legends to the subplots
axs[0, 0].legend()
axs[0, 1].legend()
axs[1, 0].legend()
axs[1, 1].legend()

# Show the plot
plt.show()

This code creates a 2×2 grid of subplots using the subplots function. Then, it plots different datasets on each subplot using the plot function. Finally, it adds legends to each subplot using the legend function without any parameters. The resulting plot displays legends for each subplot.

Matplotlib Subplots Legend

Customizing the Legend in Matplotlib

Matplotlib provides several options to customize the appearance and layout of the legend. Here are some common parameters that can be passed to the legend function:

  1. loc: Determines the location of the legend on the subplot. The possible values are 'upper left', 'upper right', 'lower left', 'lower right', 'center', and more.

  2. title: Sets the title of the legend.

  3. frameon: Specifies whether to draw a frame around the legend. The default value is True.

  4. bbox_to_anchor: Specifies the position of the legend outside the axes area. This parameter is useful when the legend occludes the plotted data.

  5. borderaxespad: Determines the padding between the axes and the legend box.

  6. shadow: Specifies whether to draw a shadow behind the legend. The default value is False.

  7. markerscale: Scales the size of the markers in the legend by the specified factor.

  8. fontsize: Sets the font size of the legend text.

  9. ncol: Specifies the number of columns in the legend. This parameter is useful when the legend contains many items.

  10. mode: Determines the behavior when the legend has more than one column. The possible values are 'expand', 'compress', and 'flood'.

Here’s an example that demonstrates the customization of the legend:

import matplotlib.pyplot as plt

# Create a figure with subplots
fig, axs = plt.subplots(1, 2)

# Plot data on the subplots
axs[0].plot([1, 2, 3], [1, 4, 9], 'ro', label='Data 1')
axs[1].plot([1, 2, 3], [10, 20, 30], 'bo', label='Data 2')

# Add legends to the subplots with customization
axs[0].legend(loc='upper right', title='Legend', frameon=False, fontsize='small')
axs[1].legend(loc='lower left', bbox_to_anchor=(0, -0.1), borderaxespad=0., ncol=2)

# Show the plot
plt.show()

Executing this code will produce a figure with two subplots. The first subplot has a legend positioned in the upper-right corner, with a custom title, no frame, and a smaller font size. The second subplot has a legend positioned in the lower-left corner outside the axes area, with zero padding, and two columns.

Matplotlib Subplots Legend

Matplotlib Subplots Legend Code Examples

Here are 10 code examples that demonstrate how to add legends to subplots in Matplotlib:

Example 1:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 2, 3], 'ro', label='Data 1')
ax.legend()
plt.show()

Output:

Matplotlib Subplots Legend

Example 2:

import matplotlib.pyplot as plt

fig, axs = plt.subplots(1, 2)
axs[0].plot([1, 2, 3], [1, 2, 3], 'ro', label='Data 1')
axs[1].plot([1, 2, 3], [1, 4, 9], 'bo', label='Data 2')
axs[0].legend()
axs[1].legend()
plt.show()

Output:

Matplotlib Subplots Legend

Example 3:

import matplotlib.pyplot as plt

fig, axs = plt.subplots(2, 2)
axs[0, 0].plot([1, 2, 3], [1, 2, 3], 'ro', label='Data 1')
axs[0, 1].plot([1, 2, 3], [1, 4, 9], 'bo', label='Data 2')
axs[1, 0].plot([1, 2, 3], [1, 8, 27], 'go', label='Data 3')
axs[1, 1].plot([1, 2, 3], [1, 16, 81], 'yo', label='Data 4')
axs[0, 0].legend()
axs[0, 1].legend()
axs[1, 0].legend()
axs[1, 1].legend()
plt.show()

Output:

Matplotlib Subplots Legend

Like(0)