Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to change the legend fontname in Matplotlib?
To change the legend fontname in Matplotlib, you can use several approaches. The most common methods are using the fontname parameter in legend() or setting font properties for individual legend text elements.
Method 1: Using fontname Parameter
The simplest way is to specify the fontname parameter directly in the legend() method ?
import numpy as np import matplotlib.pyplot as plt # Set figure size plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True # Create data points x = np.linspace(-5, 5, 100) # Plot functions plt.plot(x, np.sin(x), label="y=sin(x)") plt.plot(x, np.cos(x), label="y=cos(x)") # Add legend with custom font plt.legend(loc='upper right', fontname='Arial') plt.show()
Method 2: Using Font Properties
For more control over font properties, use FontProperties ?
import numpy as np import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties # Set figure size plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True # Create data points x = np.linspace(-5, 5, 100) # Plot functions plt.plot(x, np.sin(x), label="y=sin(x)") plt.plot(x, np.cos(x), label="y=cos(x)") # Create font properties font_prop = FontProperties(family='serif', style='italic', size=12) # Add legend with font properties plt.legend(loc='upper right', prop=font_prop) plt.show()
Method 3: Modifying Existing Legend Text
You can also change the font of an existing legend by iterating through its text elements ?
import numpy as np
import matplotlib.pyplot as plt
# Set figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create data points
x = np.linspace(-5, 5, 100)
# Plot functions
plt.plot(x, np.sin(x), label="y=sin(x)")
plt.plot(x, np.cos(x), label="y=cos(x)")
# Create legend
legend = plt.legend(loc='upper right')
# Change font for each text element
for text in legend.get_texts():
text.set_fontname('Times New Roman')
text.set_fontsize(12)
plt.show()
Available Font Options
Common font names you can use include:
-
'Arial','Times New Roman','Courier New' -
'serif','sans-serif','monospace'(generic families) -
'DejaVu Sans','Liberation Sans'(system fonts)
Comparison
| Method | Use Case | Flexibility |
|---|---|---|
fontname parameter |
Quick font change | Limited |
FontProperties |
Full control over font | High |
| Modify existing legend | Post-creation changes | Medium |
Conclusion
Use the fontname parameter for simple font changes, FontProperties for detailed control, or modify existing legend text for post-creation adjustments. The FontProperties approach offers the most flexibility for customizing legend appearance.
