1 year ago
#257944
ARGratrex
XeLaTeX setup with fontspec in matplotlib
I am preparing figures for a manuscript where I would like to have precise control over the font used for each level of text. Specifically, I want to use different weights for e.g. tick labels and the figure titles. To do this, I am using the pgf backend to drive the XeLaTeX typesetting engine.
The following code works:
#!/usr/bin/env python3
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
mpl.use("pgf")
plt.rcParams.update({
"pgf.texsystem": "xelatex",
"font.family": "serif",
"text.usetex": True,
"axes.labelsize": 7,
"font.size": 7,
"legend.fontsize": 7,
"axes.titlesize": 7,
"xtick.labelsize": 7,
"ytick.labelsize": 7,
"figure.titlesize": 10,
"pgf.rcfonts": False,
"pgf.preamble": "\n".join([
r"\usepackage{amsmath}",
r"\usepackage[no-math]{fontspec}",
r"\usepackage{xunicode}",
# r"\usepackage[version=4]{mhchem}",
r"\setmainfont{Noto}[Path=C:/Documents/Fonts/Noto/,Extension=.ttf,UprightFont=*-Light,ItalicFont=*-LightItalic]",
# r"\setsansfont{Noto}[Path=C:/Documents/Fonts/Noto/,Extension=.ttf,UprightFont=*-Light,ItalicFont=*-LightItalic]",
r"\usepackage{mathastext}",
])
})
fig,ax=plt.subplots(figsize=(5,3),dpi=1200)
x=np.linspace(0.15,0.85,100)
y=4*(x-0.5)**3-0.35*(x-0.5)
ax.plot(x,y)
ax.set_xlabel(r'\textit{x} in Li$_\mathit{x}$FePO$_4$')
ax.set_ylabel(r'Chemical potential, \textit{µ} [a.u.]')
plt.tight_layout()
fig.savefig(r'C:\Pictures\testing.png')
However, there are a number of unsatisfactory things here.
For example, I would like to use the mhchem package for the chemical formula, rather than a hodgepodge of forced italics and subscripts. Loading mhchem, however, gives an error wherein TeX asks for amsmath to be loaded first -- which it already is.
I am also setting a sans-serif font as the main font, and telling matplotlib that I want the serif fonts, because otherwise math (e.g. the ticks) are rendered in Computer Modern. I suspect this also partly intersects with the poor performance of mathastext. For example, passing the option [italic] to mathastext mercifully has no impact on the ticks, but nor does it have any impact anywhere else. Ideally, I would like math characters such as µ to correctly appear in italics, but the ticks to be upright.
I would also like to use a significantly longer LaTeX preamble, so I would rather have it in a separate TeX document that I then pass to python, but I'm not sure how to do this. (For example, in LaTeX I also use -Light.ttf for certain font sizes, and -SemiCondensed.ttf for others, etc.)
python
matplotlib
xelatex
chemistry
fontspec
0 Answers
Your Answer