How to change Legend Font Size in Marplolib?
0 738
Introduction
When you're working with data visualizations in Matplotlib, making the legend readable is important for communicating your message clearly. One of the most common tweaks is adjusting the font size of the legend text. Matplotlib provides a few simple ways to do this using built-in options.
Method 1: Change Font Size with fontsize Parameter
The most straightforward way to control the legend font size is to pass the fontsize argument directly into the legend() function. You can use specific sizes like integers or descriptive strings like "small", "medium", or "large".
import matplotlib.pyplot as plt
x = [1, 2, 3]
y1 = [1, 4, 9]
y2 = [2, 3, 5]
plt.plot(x, y1, label='Curve A')
plt.plot(x, y2, label='Curve B')
plt.legend(fontsize=12) # Set legend font size to 12 points
plt.show()
This approach works well for most use cases and keeps the code simple and readable.
Method 2: Use Font Properties for More Control
If you want even more control over the font styling, including size, weight, and family, you can use the prop parameter with a dictionary of font settings.
plt.legend(prop={'size': 16, 'weight': 'bold'})
This method is useful when you need a consistent font style across multiple visual elements, not just the legend.
Method 3: Set Default Font Size Globally
Instead of changing the font size for each legend manually, you can set a default legend font size for your entire script using matplotlib.rcParams.
import matplotlib.pyplot as plt
plt.rcParams['legend.fontsize'] = 14 # Apply globally
plt.plot(x, y1, label='Global Setting Example')
plt.legend()
plt.show()
This is especially useful if you're creating multiple plots and want all legends to follow the same style automatically.
Conclusion
Changing the font size of a legend in Matplotlib is quick and flexible. You can do it inline using fontsize, apply detailed styling with prop, or set it globally using rcParams. No matter which method you choose, adjusting legend text helps make your plots easier to read and more professional-looking.
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