Customizing Legends in Matplotlib Plots

When creating plots with multiple lines or elements, a legend is often used to provide context and explain what each line represents. By default, Matplotlib places the legend within the plot area, but there are times when you might want to move it outside of the plot for better readability or aesthetics. In this tutorial, we’ll explore how to customize the placement and appearance of legends in Matplotlib plots.

Basic Legend Placement

To start with, let’s create a simple plot with multiple lines and add a legend using the legend() method.

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)

for i in range(5):
    ax.plot(x, i * x, label='$y = %ix$' % i)

ax.legend()

plt.show()

This will create a plot with the legend placed inside the plot area. However, we can move the legend outside of the plot by using the bbox_to_anchor parameter.

Moving the Legend Outside the Plot

The bbox_to_anchor parameter allows us to specify the location of the legend in relation to the plot area. For example, to place the legend to the right of the plot, we can use (1.1, 1.05) as the anchor point.

ax.legend(bbox_to_anchor=(1.1, 1.05))

This will shift the legend slightly outside the axes boundaries. We can also adjust the loc parameter to change the alignment of the legend with respect to the anchor point.

Adjusting Legend Size and Font

To reduce the size of the legend box, we can decrease the font size of the text inside the legend by using the fontsize parameter.

ax.legend(fontsize='small')

Alternatively, we can shrink the current plot’s width or height to make room for the legend outside of the axis area. This can be done by adjusting the position of the axes using set_position().

Shrink Current Axis

To shrink the current axis by 20% and place a legend to the right, we can use the following code:

box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

Similarly, to shrink the plot vertically and place a horizontal legend at the bottom, we can use:

box = ax.get_position()
ax.set_position([box.x0, box.y0 + box.height * 0.1,
                 box.width, box.height * 0.9])
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),
          fancybox=True, shadow=True, ncol=5)

Conclusion

Customizing the placement and appearance of legends in Matplotlib plots can greatly enhance the readability and visual appeal of your graphs. By using the bbox_to_anchor parameter, adjusting font sizes, and shrinking the plot area, you can create professional-looking plots with well-placed legends.

For more information on customizing legends, refer to the Matplotlib legend guide.

Leave a Reply

Your email address will not be published. Required fields are marked *