4
votes

My goal is to use a particular font, for example Nimbus Sans L or Tex Gyre Heros, for all the text (regular as well as math) in a matplotlib figure. These two fonts are available as .otf files. When I run the code below, the png image is produced correctly, but in the pdf the letters of the title and axis numbers have extra space between them. It seems that changing the font size from the default 10pt produces strange scaling.

pdf with problems:

enter image description here

png okay:

enter image description here

What I've tried: It seems to work fine with .ttf fonts.

What I'm using: matplotlib 2.0.0, python 3.5.2

Example code:

import matplotlib as mpl

import numpy as np
x = np.linspace(-3, 10, 100)
ymodel = x**2
ydata = ymodel + 20 * (np.random.rand(len(x)) - 0.5)

font = 'tex gyre heros'  # an open type font

mpl.rcParams['font.sans-serif'] = font
mpl.rc('mathtext', fontset='custom', it=font + ':italic')
mpl.rc('font', size=13)  # change font size from default 10

import matplotlib.pyplot as plt
plt.figure()    
plt.plot(x, ydata, 'o')
plt.plot(x, ymodel)
plt.xlabel("Something for the $x$ axis (units)")
plt.ylabel("The $y$ axis (units)")
plt.title("{}".format(font.upper()))
plt.text(0, 80, "Some math: $\chi_{13}=-3\pi\psi\Delta_A\\times\omega + x^2$")

plt.savefig("fig_" + font.lower() + ".pdf", bbox_inches='tight')
plt.savefig("fig_" + font.lower() + ".png", bbox_inches='tight', dpi=300)
1

1 Answers

1
votes

This sounds like the bug described in this issue discussion. If so, the bug has been patched and the solution is to upgrade matplotlib to version 2.0.1 or higher.