Matplotlib - Font Properties



What are Font properties?

In Matplotlib library font properties are attributes that determine the appearance and styling of text elements within plots and figures. These properties include various aspects such as font family, size, weight, style and other settings that affect the visual presentation of text.

Key Font Properties in Matplotlib

Font Family

The Font family specifies the typeface or used for text elements. Common families include serif, sans-serif, monospace etc.

  • serif − Fonts with decorative strokes often used for a more traditional or formal appearance.
  • sans-serif − Fonts without decorative strokes known for a clean and modern look which are commonly used for readability.
  • monospace − Fonts where each character occupies the same amount of horizontal space, often used for code or tabular data.
  • Custom or Specific Fonts − Users can also use custom fonts installed on their system or provide font paths for specific typefaces.

Font Size

The Font size determines the size of the text in points (pt) influencing readability and visibility. Font size is specified in points (pt) where 1 point is approximately 1/72 inch. Matplotlib uses points as a standard unit for font size by allowing for consistency across different devices and display resolutions.

Font Weight

The Font weight controls the thickness or boldness of the text. Options range from normal to bold. It allows users to control the visual emphasis of text elements such as labels, titles, annotations and other textual components.

Font Weight Options

  • normal − Specifies normal font weight.
  • bold − Specifies a bold font weight.
  • Integer Values − Some fonts support numeric values ranging from 100 to 900 to specify the weight level.

Font Style

The Font style specifies the style of the text such as normal, italic or oblique. It allows users to control the slant or style of the text elements such as labels, titles, annotations and other textual components.

Font Style Options

  • normal − Specifies normal font style (no slant or italicization).
  • italic − Specifies italic font style slanting the characters.
  • oblique − Similar to italic but may differ slightly in appearance in some fonts.

Setting Font Properties in Matplotlib

The following are the ways to set the font properties in matplotlib.

Global Configuration (using plt.rcParams)

This is used to configure default font properties for all text elements in a plot or figure.

Example

import matplotlib.pyplot as plt
# Set global font properties
x = [2,3,4,6]
y = [9,2,4,7]
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.size'] = 8
plt.rcParams['font.weight'] = 'normal'
plt.rcParams['font.style'] = 'italic'
plt.plot(x,y)
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.title("Setting fonts globally")
plt.show()
Output
Setting Fonts Globally

Individual Text Elements

Through this method we can set font properties for specific text elements within a plot.

Example

import matplotlib.pyplot as plt
# Set Individual font properties
x = [2,3,4,6]
y = [9,2,4,7]
plt.plot(x,y)
plt.xlabel('X-axis Label', fontsize=14, fontweight='bold', fontstyle='italic')
plt.ylabel('Y-axis Label', fontsize=14, fontweight='bold', fontstyle='normal')
plt.title("Setting fonts Individually")
plt.show()
Output
Setting Fonts

Importance of Font Properties

The below are the importance of the font properties.

Readability

Proper font selection and size enhance the legibility of text elements.

Aesthetics

Font styles and families contribute to the visual appeal of plots.

Communication

Font properties aid in conveying emphasis or context within visualizations.

Using Font Properties for Customization

  • Adjusting font properties allows users to tailor the appearance of text to match the requirements of the visualization or presentation.
  • Consistent and appropriate use of font properties ensures a visually cohesive and informative display of textual information within plots and figures.

Finally we can font properties in Matplotlib library provide users with the flexibility to customize text appearance, ensuring clarity, readability and visual appeal in visualizations. These properties enable precise control over how text elements are displayed within plots helping effectively communicate information to viewers.

Multiple font sizes in one label

In this example we use multiple font sizes in one label in Python with the help of fontsize parameter in title() method.

Example

import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-5, 5, 100)
y = np.cos(x)
plt.plot(x, y)
fontsize = 20
plt.title("$bf{y=cos(x)}$", fontsize=fontsize)
plt.axis('off')
plt.show()
Output
multiple_font

Change the text color of font in the legend

Here in this example we will change the text color of the font in the legend.

Example

import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-2, 2, 100)
y = np.exp(x)
plt.plot(x, y, label="y=exp(x)", c='red')
leg = plt.legend(loc='upper left')
for text in leg.get_texts():
   text.set_color("green")
plt.show()
Output
legend_font_size

Change the default font color for all text

In this example we will change the default font color for all the text in the plot.

Example

import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
print("Default text color is: ", plt.rcParams['text.color'])
plt.rcParams.update({'text.color': "red",
   'axes.labelcolor': "green"})
plt.title("Title")
plt.xlabel("X-axis")
plt.show()
Output

Default text color is: black

default_color

Change the font size of ticks of axes object

In this example we will change the default font color for all the text in the plot.

Example

import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-2, 2, 10)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y, c='red', lw=5)
ax.set_xticks(x)
for tick in ax.xaxis.get_major_ticks():
   tick.label.set_fontsize(14)
   tick.label.set_rotation('45')
plt.tight_layout()
plt.show()
Output
axes_object

Increase the font size of the seaborn plot legend

In this example we increase the font size of the legend in a Seaborn plot, we can use the fontsize variable and can use it in legend() method argument.

Example

import pandas
import matplotlib.pylab as plt
import seaborn as sns
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pandas.DataFrame(dict(
   number=[2, 5, 1, 6, 3],
   count=[56, 21, 34, 36, 12],
   select=[29, 13, 17, 21, 8]
))
bar_plot1 = sns.barplot(x='number', y='count', data=df, label="count", color="red")
bar_plot2 = sns.barplot(x='number', y='select', data=df, label="select", color="green")
fontsize = 20
plt.legend(loc="upper right", frameon=True, fontsize=fontsize)
plt.show()
Output
seaborn_legend
Advertisements