0
0
Matplotlibdata~5 mins

Font properties customization in Matplotlib

Choose your learning style9 modes available
Introduction

Changing font properties helps make your charts easier to read and look nicer.

You want to make the title of a chart bigger and bold.
You need to change the font style of axis labels to italic.
You want to use a specific font family like 'Comic Sans' for fun charts.
You want to adjust the font size of legend text to fit better.
You want to highlight some text by changing its color and weight.
Syntax
Matplotlib
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

font = FontProperties(family='serif', style='italic', weight='bold', size=14, color='blue')
plt.title('My Title', fontproperties=font)
plt.xlabel('X axis', fontproperties=font)
plt.ylabel('Y axis', fontproperties=font)
plt.show()

You create a FontProperties object to set font details.

Pass this object to text elements like title, xlabel, ylabel using fontproperties.

Examples
Title with serif font, size 16, and bold weight.
Matplotlib
font = FontProperties(family='serif', size=16, weight='bold')
plt.title('Bold Serif Title', fontproperties=font)
X axis label with italic sans-serif font.
Matplotlib
font = FontProperties(family='sans-serif', style='italic', size=12)
plt.xlabel('Italic X Label', fontproperties=font)
Y axis label with light weight monospace font.
Matplotlib
font = FontProperties(family='monospace', size=10, weight='light')
plt.ylabel('Light Monospace Y Label', fontproperties=font)
Sample Program

This program plots a simple line chart. The title uses a serif italic bold font in dark red color. The axis labels use a green sans-serif font with normal weight.

Matplotlib
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

# Create font properties for title
title_font = FontProperties(family='serif', style='italic', weight='bold', size=18, color='darkred')

# Create font properties for axis labels
label_font = FontProperties(family='sans-serif', size=14, weight='normal', color='green')

# Sample data
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]

plt.plot(x, y)
plt.title('Sales Over Time', fontproperties=title_font)
plt.xlabel('Month', fontproperties=label_font)
plt.ylabel('Sales', fontproperties=label_font)
plt.show()
OutputSuccess
Important Notes

Not all fonts are available on every computer; if a font family is missing, matplotlib uses a default font.

You can also set font properties directly using keyword arguments like fontsize, fontweight, and color without FontProperties.

Use plt.rcParams to set default font styles for all plots.

Summary

Font properties control how text looks in your plots.

Use FontProperties to customize font family, style, weight, size, and color.

Apply font properties to titles, labels, and other text elements for better visuals.