How to change the vertical spacing between legend entries in Matplotlib?
0 188
Introduction
Legends in Matplotlib help identify different data series on a plot. When dealing with multiple legend entries, spacing between them and the font size play a big role in readability. In this guide, we’ll explore how to adjust vertical spacing between legend entries and how to change the legend font size for better visual appeal.
Changing Vertical Spacing Between Legend Entries
Matplotlib’s legend()
function includes the labelspacing
parameter, which controls the vertical distance between the legend items. Increasing this value spreads out the entries, while decreasing it brings them closer together.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y1 = [1, 4, 2, 3]
y2 = [4, 1, 3, 2]
plt.plot(x, y1, label='Data A')
plt.plot(x, y2, label='Data B')
# Set vertical spacing between legend entries
plt.legend(labelspacing=1.8)
plt.show()
Here, labelspacing=1.8
creates more space between legend entries. The default value is usually around 0.5, so this significantly increases spacing.
Modifying Legend Font Size
Along with spacing, the font size of the legend text can be adjusted to make it more readable or better fit the plot’s design. Use the fontsize
parameter inside the legend()
function to control this.
plt.plot(x, y1, label='Data A')
plt.plot(x, y2, label='Data B')
# Set legend font size
plt.legend(fontsize='large')
plt.show()
You can specify font size using common string options like 'small'
, 'medium'
, 'large'
, or by passing an integer value representing the size in points (e.g., fontsize=12
).
Combining Vertical Spacing and Font Size
Both parameters can be used together to tailor the legend’s appearance exactly to your needs.
plt.plot(x, y1, label='Data A')
plt.plot(x, y2, label='Data B')
plt.legend(labelspacing=1.5, fontsize=14)
plt.show()
Conclusion
Customizing the legend in Matplotlib by adjusting vertical spacing and font size greatly improves plot clarity and aesthetics. These simple tweaks allow you to make your visualizations more professional and easier to interpret.
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!

Share:
Comments
Waiting for your comments