keflavich
keflavich

Reputation: 19195

How can I load a unicode font into matplotlib?

I'm trying to plot unicode symbols. I've tried a variety of approaches and always get stuck with bitstream vera sans, which doesn't have the symbols I need.

I have unsuccessfully tried deleting the font cache (~/.matplotlib/fontList.*cache), loading the font directly from file (e.g. How to use a (random) *.otf or *.ttf font in matplotlib?), and some other SO suggestions that I've now lost.

>>> import matplotlib
>>> matplotlib.use('agg')
>>> import matplotlib.font_manager as font_manager
>>> prop = font_manager.FontProperties('/Library/Fonts/Arial Unicode.ttf')
>>> prop.get_name()
/Users/adam/anaconda/envs/astropy27/lib/python2.7/site-packages/matplotlib/font_manager.py:1279: UserWarning: findfont: Font family ['/Library/Fonts/Arial Unicode.ttf'] not found. Falling back to Bitstream Vera Sans
  (prop.get_family(), self.defaultFamily[fontext]))
'Bitstream Vera Sans'

How can I load this font, or at least something nearly equivalent?

Upvotes: 1

Views: 1366

Answers (2)

T .
T .

Reputation: 396

The problem is in line

>>> prop = font_manager.FontProperties('/Library/Fonts/Arial Unicode.ttf')

You're setting the first argument, family, but you want to set the file name, fname. So this instead:

>>> prop = font_manager.FontProperties(fname='/Library/Fonts/Arial Unicode.ttf')

Upvotes: 1

Timothy Dalton
Timothy Dalton

Reputation: 1390

This could work, it did at least for me:

import matplotlib as mpl
import matplotlib.font_manager as font_manager

path_font = '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/mpl-data/fonts/ttf/cmunrm.ttf'
prop = font_manager.FontProperties(fname=path_font)
#print prop.get_name()
mpl.rcParams['font.family'] = prop.get_name()
mpl.rcParams['font.size'] = 16.
mpl.rcParams['axes.labelsize'] = 12.
mpl.rcParams['xtick.labelsize'] = 12.
mpl.rcParams['ytick.labelsize'] = 12.

Upvotes: 1

Related Questions