André Puel
André Puel

Reputation: 9189

How to change the font in matplotlib using an absolute path?

Using matplotlib.rc I can change the font family and which fonts are in each family.

rc('font',family='serif')
rc('font',serif='Helvetica')

However, I have a specific TTF font file that is not installed in the system and I would like to use it. Is there any way to specify an absolute path to the font configuration?

Upvotes: 2

Views: 637

Answers (1)

DrV
DrV

Reputation: 23540

There is a way to use a font which is not installed into the system. For example:

import matplotlib.font_manager
import matplotlib.pyplot as plt
import matplotlib.text

# load the font properties
font = matplotlib.font_manager.FontProperties(fname="/tmp/Warenhaus-Standard.ttf")
font.set_size(28)

# draw a figure
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim(0,1)
ax.set_ylim(0,1)
ax.add_artist(matplotlib.text.Text(0.05, 0.45, "Special Font (Warenhauser)", fontproperties=font))

Creates:

enter image description here

If you look at the code and like the PyLab-style of using the stateful interface, the important part of the code is still the same (font=... and the kwarg fontproperties=font).

There are a couple of caveats, though. Maybe the most important is that the special font is not necessarily displayed on-screen if it is not installed (if the backend uses the OS fonts, as at least the MacOSX backend does), but it is still saved by savefig.

It might be quite instructive to have a look at matplotlib.font_manager documentation. The font management is actually quite sophisticated.

Upvotes: 2

Related Questions