1

I am trying to get a standardised method to import plots from matplotlib into my LaTeX document, borrowing text formatting from the main document (so I want to avoid pure PDF). I am currently exporting the figure as PGF.

When I save the figure as a PGF the settings (linewidths, markersizes, annotation text sizes, etc.) do carry over properly, but the font is not inherited from the document.

MWE:

Create the figure in python:

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams.update({'text.usetex': True})

x = np.random.random(10)
y = np.random.random(10)

plt.figure()
plt.plot(x, y, 'o')
plt.xlabel('my xlabel')
plt.ylabel('my ylabel')

plt.savefig('D:/_Current Work/fig.pgf')

LaTeX:

\documentclass{article}
\usepackage{pgf}
\usepackage{pgfplots}

\renewcommand\familydefault{\sfdefault}

\begin{document}

\input{"D:/_Current Work/fig.pgf"}

\end{document}

The figure created will not change the font used in the tick labels and axes labels regardless of whether I include or omit the \renewcommand\familydefault{\sfdefault} to change the font to sans-serif.

I've read many other posts on the forum about these two tools but it seems like this should work without any problems so I assume I am missing something basic.

EDIT

A few users suggested this question is a duplicate of Typeset mathematical symbols also in sans serif font?. My problem seems to be the exact opposite of the question in the link: my math is being renderred according to the global math font correctly, but the normal text is not.

  • I believe I have found the problem. It is to do with matplotlib's exporting to a PGF, which forces a font family upon all text, even if none is specified (in which case it uses the default sans-serif family). The question now becomes how do I stop matplotlib from adding a font family to text entries. This is a question for StackOverflow, not TeX.StackExchange. I have posted a new question there – krg May 23 at 17:30
  • As a temporary fix, you can replace every occurrence of sffamily with rmfamily in the figure using sed -i 's/sffamily/rmfamily/g' fig.pgf (or sed -i '' 's/sffamily/rmfamily/g' fig.pgf on macos) – erik May 23 at 20:42
  • A similar comment was made in StackOverflow. The problem is that I do not want to specify a font at all, but I imagine your macro can be rewritten to just delete \sffamily rather than replace it with \rmfamily. Alternatively, a user suggested to use \renewcommand\sffamily{} inside the figure enviornment, which has a similar effect. – krg May 24 at 10:05
  • Maybe just replace sffamily with normalfont. – erik May 24 at 16:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.