Matplotlib Math Fontfamily

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

This lab will guide you through the process of changing the family of fonts for each individual text element in a plot using the Python Matplotlib library.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.

Import Required Libraries

First, we need to import the required libraries. We will be using Matplotlib to create the plot and to manipulate the text elements.

import matplotlib.pyplot as plt

Create the Plot

Now, we will create a simple plot for the background using the plot() function.

fig, ax = plt.subplots(figsize=(6, 5))
ax.plot(range(11), color="0.9")

Set Text in the Plot

Next, we will set the text in the plot using the text() function. We will use the math_fontfamily parameter to change the font family for each individual text element.

## A text mixing normal text and math text.
msg = (r"Normal Text. $Text\ in\ math\ mode:\ "
       r"\int_{0}^{\infty } x^2 dx$")

## Set the text in the plot.
ax.text(1, 7, msg, size=12, math_fontfamily='cm')

## Set another font for the next text.
ax.text(1, 3, msg, size=12, math_fontfamily='dejavuserif')

Set Font for the Title

We can also change the font family for the title using the math_fontfamily parameter.

ax.set_title(r"$Title\ in\ math\ mode:\ \int_{0}^{\infty } x^2 dx$",
             math_fontfamily='stixsans', size=14)

Display the Plot

Finally, we will display the plot using the show() function.

plt.show()

Summary

In this lab, we learned how to change the family of fonts for each individual text element in a plot using the math_fontfamily parameter in Matplotlib. This feature allows us to customize the look of our plots and make them more visually appealing.

Other Python Tutorials you may like