I am exporting matplotlib figures as PGF to use in LaTeX.
matplotlib seems to add a \sffamily
addition to every text entry (axes labels, ticks, legend entries, annotations) when saving the figure as a PGF. This will stop it from properly inheriting the font from the global document font.
The text can inheret the font from the global document font if it is from the same family, but it will revert to the default sffamily font if the global font is from a different family.
I believe I have isolated the problem: if I edit the PGF document and simply remove the \sffamily
part of any text entry, the problem no longer persists and the global font is inherited. The deletion doesn't prevent LaTeX from compiling it properly, and I get no errors.
Because of the above finding, I believe the problem has nothing to do with rcParams
or any LaTeX preamble (both in python or in the actual LaTeX document).
I just tried it on the simplest possible plot and was able to reproduce the problem:
import matplotlib.pyplot as plt
fig = plt.figure()
plt.xlabel('a label')
fig.savefig('fig.pgf')
And pgf document will contain the following line:
\pgftext[x=3.280000in,y=0.240809in,,top]{\color{textcolor}\sffamily\fontsize{10.000000}{12.000000}\selectfont a label}%
so the \sffamily
is added. Rendering this in LaTeX will force a sans-serif font. Removing the \sffamily
and rendering it will allow it to inherit the font family.
Is there a way to avoid the inclusion of a font family in the PGF output of matplotlib?
Building on https://matplotlib.org/users/pgf.html#font-specification you could use:
import matplotlib as mpl
import matplotlib.pyplot as plt
pgf_with_rc_fonts = {
"font.family": "serif",
}
mpl.rcParams.update(pgf_with_rc_fonts)
fig = plt.figure()
plt.xlabel('a label')
fig.savefig('fig.pgf')
This way \rmfamily
is used instead of \sffamily
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With