[Tex/LaTex] Configure the Matplotlib figure size so that the font within the graphics matches the font in the text

graphics

I would like to configure the size of a figure produced by Matplotlib so that the font within the graphics matches the font size in the text.

The following Python script produces the figure using Tex fonts.

import numpy as np
import pylab as pl
import matplotlib

matplotlib.rcParams["text.usetex"] = True
matplotlib.rcParams["font.family"] = "serif"
matplotlib.rcParams["font.size"] = "18"

x = np.linspace(0.0, 2.0 * np.pi, 1000)
y = np.sin(x)
#
pl.figure(figsize=(4, 3))
pl.plot(x, y, "-")
pl.xlabel("x")
pl.ylabel("y")
pl.title("The sine function")
pl.savefig("sine-function.pdf", bbox_inches="tight")

Then I created a LaTeX document which inserts this figure.

\documentclass{article}
\usepackage[pdftex]{graphicx}
\usepackage{lipsum}
\begin{document}
\begin{center}
\includegraphics[width=\textwidth]{sine-function.pdf}
\end{center}
\lipsum[1]
\end{document}

This produces:

The result

The figure is much larger than required. I could downsize it e.g. with width=0.5\textwidth, but this is unsatisfactory, because, no matter how I set the width parameter, I cannot be sure that the font size in the text matches the font size in the figure.

How to configure this correctly?

Best Answer

The trick is to configure the font size correctly right from Matplotlib. The correct script is the following. The font size is set to 10. In order to produce a correct graph, I add to downsize the figure with the figsize argument.

import numpy as np
import pylab as pl
import matplotlib

matplotlib.rcParams["text.usetex"] = True
matplotlib.rcParams["font.family"] = "serif"
matplotlib.rcParams["font.size"] = "10"

x = np.linspace(0.0, 2.0 * np.pi, 1000)
y = np.sin(x)
#
pl.figure(figsize=(2.0, 1.5))
pl.plot(x, y, "-")
pl.xlabel("x")
pl.ylabel("y")
pl.title("The sine function")
pl.savefig("sine-function.pdf", bbox_inches="tight")

Then I used the following tex document. Since the font size in the PDF is 10, I do not have to change its width.

\documentclass{article}
\usepackage[pdftex]{graphicx}
\usepackage{lipsum}
\begin{document}
\begin{center}
\includegraphics{sine-function.pdf}
\end{center}
\lipsum[1]
\end{document}

This produces:

The correct result

which is the correct result.

Related Question