iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🎨

Matplotlib: Creating High-Quality Graphs with LaTeX and Custom Font Settings

に公開

1. Motivation

Aesthetic quality in data visualization is not the core essence of information transmission, but it is better to have it. Visually refined graphs give the impression that researchers pay attention to detail, which helps establish the credibility of the reported content. Furthermore, they remain in the reader's memory, ultimately contributing to the improvement of information transmission efficiency and comprehension.

Matplotlib, widely used as a modern data visualization tool, has become an indispensable library in the fields of scientific computing and data science due to its extensive customizability and high expressive power. However, matplotlib's standard font (DejaVu Sans) has a somewhat casual impression in business and academic contexts. Mathematical expressions are also processed with a cheap text-based look, making them look clearly out of place in papers or formal reports.

Default graph output

plt.title('Distribution of Petal Length')
plt.xlabel('Petal Length $L$ [cm]')
plt.ylabel('Frequency $f$')
plt.legend()

In this article, I will explain how to improve the quality of graphs created with matplotlib by rendering mathematical formulas using LaTeX and changing fonts to those suitable for paper and report quality.

2. Enabling \LaTeX Notation

First, let's enable rendering of text such as titles and XY-axis labels using \LaTeX (pdflatex). Install pdflatex on your system so that it can be executed from the command line.

The following example shows how to install the necessary libraries on Ubuntu 24.02. The same method can be used for installation on Windows WSL2.

sudo apt -y install texlive-lang-japanese texlive-fonts-extra dvipng

pdflatex --version
# pdfTeX 3.141592653-2.6-1.40.25 (TeX Live 2023/Debian)
# ...

After the installation is complete, it is recommended to create a simple LaTeX document and verify that the pdflatex command functions correctly.

To use LaTeX typesetting in matplotlib, enable text.usetex in rcParams. By adding the following code before execution, all text elements will be processed by the LaTeX engine.

regular text

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

Specifying serif for font.family will result in a serif font like Times. While it has less "visual impact" than the default sans-serif, it is a good choice if you want to give a smarter and more intellectual impression based on your preference.

regular text

plt.rcParams.update({
  "text.usetex": True,
  "font.family": "serif",
  "pgf.texsystem": "pdflatex"
})

For graphs used in papers written in LaTeX, enabling LaTeX typesetting in this way maintains visual consistency with the main text and improves the quality of the entire document. In particular, since mathematical symbols such as \alpha, \int, \sum perfectly match the main text, diagrams can be naturally integrated without standing out from the document.

Note that matplotlib supports output in PGF format, which can be directly imported into LaTeX documents as shown below. This method is convenient because the font of the diagram perfectly matches the font settings of the document, and font size or colors can be adjusted later on the LaTeX side.

# Save in PGF format
plt.savefig('figure.pgf')
\documentclass{article}
\usepackage{pgf}
\begin{document}
\begin{figure}[htbp]
  \centering
  \input{figure.pgf}
  \caption{A figure generated by matplotlib above.}
  \label{fig:sample}
\end{figure}
\end{document}

3. Changing to Preferred Fonts

While the quality provided by LaTeX is already sufficiently beautiful, let's take one step further here to stand out from the competition.

For example, by using Helvetica, which is used in world-class designs and brand logos, or Neue Haas Grotesk (the basis for Helvetica), the impression of your graphs will become even more refined. I often use the latter, as it becomes available by installing the standard "Supplemental European Language Fonts" on Windows (I believe it's fine to use it on WSL running on the same Windows, but please be very careful regarding font licenses).

Neue Haas Grotesk Text Pro

First, install the target font on your system. On Ubuntu 24.02, you can install it to your personal directory as follows:

mkdir -p "${HOME}/.local/share/fonts"
cp NeueHaasDisplay-Roman.ttf "${HOME}/.local/share/fonts"

fc-cache -fv

Once the font cache is updated, check if the system recognizes it.

$ fc-list 'Neue Haas Grotesk Display Pro'
/home/torao/.local/share/fonts/NeueHaasDisplay-Roman.ttf: Neue Haas Grotesk Display Pro:style=55 Roman

Additionally, since pdflatex used in the previous section does not support changing fonts, you will need to use xelatex instead.

sudo apt -y install texlive-xetex

By using xelatex, you can specify setsansfont within a LaTeX document, allowing you to change the font used for the sans-serif typeface to your desired font.

\documentclass{article}
\usepackage{fontspec}
\setsansfont{Neue Haas Grotesk Display Pro}
\begin{document}
  \textsf{Distribution of Petal Length}
\end{document}
xelatex title.tex

In matplotlib, you can also specify the sans-serif font by adding this preamble.

regular text

matplotlib.use('pgf')
plt.rcParams.update({
  "text.usetex": True,
  "pgf.texsystem": "xelatex",
  "pgf.rcfonts": False,
  "pgf.preamble": r"\usepackage{fontspec}\setsansfont{Neue Haas Grotesk Display Pro}"
})

The configuration details are as follows:

  1. First, matplotlib.use('pgf') changes the matplotlib backend to PGF, which is a graphics package integrated with LaTeX.
  2. Next, "text.usetex": True instructs all text elements (titles, axis labels, legends, etc.) to be rendered by the LaTeX engine.
  3. "pgf.texsystem": "xelatex" specifies the LaTeX engine.
  4. "pgf.rcfonts": False disables matplotlib's font settings and prioritizes the LaTeX-side font configuration. This allows the font specified in the preamble to be applied.
  5. Finally, "pgf.preamble": ... inserts a preamble to use Neue Haas Grotesk as the sans-serif font.

Summary

In this article, we took a step beyond matplotlib's default settings and explained additional techniques for modifying text representation to create graphs suitable for academic papers and business reports. The introduction of LaTeX typesetting significantly improves the expression of mathematical formulas, and the use of sophisticated fonts like Helvetica and Neue Haas Grotesk further enhances visual quality.

Aesthetics play a crucial role in conveying your message. Beautiful, consistent diagrams impress upon the reader the thoroughness and expertise behind your research, making the entire report feel like something worth reading. We hope you will utilize these high-quality graphs to create even more persuasive reports.

GitHubで編集を提案

Discussion