Creating a Plot with Custom Fonts

PythonPythonBeginner
Practice Now

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

Introduction

In this lab, you will learn how to create a plot with custom fonts using the Python Matplotlib library. You will be introduced to the pgf.texsystem parameter that allows you to use LaTeX to customize the font family of your plot.

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/AdvancedTopicsGroup(["`Advanced Topics`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/BasicConceptsGroup -.-> matplotlib/saving_figures("`Saving Figures to File`") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("`Line Plots`") matplotlib/AdvancedTopicsGroup -.-> matplotlib/matplotlib_config("`Customizing Matplotlib Configurations`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills matplotlib/importing_matplotlib -.-> lab-48863{{"`Creating a Plot with Custom Fonts`"}} matplotlib/figures_axes -.-> lab-48863{{"`Creating a Plot with Custom Fonts`"}} matplotlib/saving_figures -.-> lab-48863{{"`Creating a Plot with Custom Fonts`"}} matplotlib/line_plots -.-> lab-48863{{"`Creating a Plot with Custom Fonts`"}} matplotlib/matplotlib_config -.-> lab-48863{{"`Creating a Plot with Custom Fonts`"}} python/lists -.-> lab-48863{{"`Creating a Plot with Custom Fonts`"}} python/tuples -.-> lab-48863{{"`Creating a Plot with Custom Fonts`"}} python/dictionaries -.-> lab-48863{{"`Creating a Plot with Custom Fonts`"}} python/importing_modules -.-> lab-48863{{"`Creating a Plot with Custom Fonts`"}} python/data_visualization -.-> lab-48863{{"`Creating a Plot with Custom Fonts`"}} python/build_in_functions -.-> lab-48863{{"`Creating a Plot with Custom Fonts`"}} end

Import Matplotlib and Set the pgf.texsystem Parameter

First, you need to import the Matplotlib library and set the pgf.texsystem parameter to pdflatex. This parameter allows you to use LaTeX to customize the font family of your plot.

import matplotlib.pyplot as plt

plt.rcParams.update({
    "pgf.texsystem": "pdflatex",
})

Define the Font Family

Next, you need to define the font family that you want to use in your plot. In this example, we will use the cmbright font family.

plt.rcParams.update({
    "pgf.texsystem": "pdflatex",
    "pgf.preamble": "\n".join([
         r"\usepackage[utf8x]{inputenc}",
         r"\usepackage[T1]{fontenc}",
         r"\usepackage{cmbright}",
    ]),
})

Create the Plot

Now, you can create your plot using the plt.subplots() function. In this example, we will create a simple line plot.

fig, ax = plt.subplots(figsize=(4.5, 2.5))

ax.plot(range(5))

Add Text to the Plot

You can add text to your plot using the ax.text() function. In this example, we will add text with different font families.

ax.text(0.5, 3., "serif", family="serif")
ax.text(0.5, 2., "monospace", family="monospace")
ax.text(2.5, 2., "sans-serif", family="sans-serif")
ax.set_xlabel(r"µ is not $\mu$")

Adjust the Layout and Save the Plot

Finally, you can adjust the layout of your plot and save it to a file using the fig.tight_layout() and fig.savefig() functions, respectively.

fig.tight_layout(pad=.5)

fig.savefig("pgf_texsystem.pdf")
fig.savefig("pgf_texsystem.png")

Summary

In this lab, you learned how to create a plot with custom fonts using the Python Matplotlib library. You used the pgf.texsystem parameter to set the font family of your plot and the ax.text() function to add text with different font families. You also learned how to adjust the layout of your plot and save it to a file.

Other Python Tutorials you may like