Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a (random) *.otf or *.ttf font in matplotlib?

How can I use any type of font in my font library on my computer (e.g. *otf or *ttf) in all my matplotlib figures?

like image 523
ruben baetens Avatar asked Oct 11 '11 13:10

ruben baetens


People also ask

How do I use TTF font in Python?

To permanently install the font into Windows, you need to copy the font file into Fonts folder (C:\Windows\Fonts, or %userprofile%\AppData\Local\Microsoft\Windows\Fonts for per-user folder) and then add a key in registry at HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Fonts (or HKEY_CURRENT_USER\ ...

What font is used in matplotlib?

Matplotlib uses DejaVu Sans in part because it includes glyphs for a very wide range of symbols, especially mathematical symbols. However in our opinion, DejaVu Sans is not very aesthetically pleasing.


2 Answers

See the example here: http://matplotlib.sourceforge.net/examples/api/font_file.html

In general, you'd do something like this if you're wanting to use a specific .ttf file. (Keep in mind that pointing to a specific font file is usually a bad idea!)

import matplotlib.font_manager as fm import matplotlib.pyplot as plt  fig, ax = plt.subplots() ax.plot(range(10))  prop = fm.FontProperties(fname='/usr/share/fonts/truetype/groovygh.ttf') ax.set_title('This is some random font', fontproperties=prop, size=32)  plt.show() 

enter image description here

Usually, you'd just point to the name of the font, and let matplotlib worry about finding the specific file. E.g.

import matplotlib.pyplot as plt  plt.plot(range(10)) plt.title('This is some random font', family='GroovyGhosties', size=32)  plt.show() 

If you want to have matplotlib always use a particular font, then customize your .matplotlibrc file. (font.family is what you'd want to set. Note that you should specify the name of the font, not the path to a specific .ttf file.)

As an example of doing this dynamically (i.e. without setting up a specific .matplotlibrc file):

import matplotlib as mpl mpl.rcParams['font.family'] = 'GroovyGhosties'  import matplotlib.pyplot as plt  plt.plot(range(10)) plt.title('Everything is crazy!!!', size=32) plt.show() 

enter image description here

like image 107
Joe Kington Avatar answered Oct 11 '22 15:10

Joe Kington


On *nix, you can use all your system fonts by enabling matplotlib's fontconfig backend.

However matplotlib does not really talk to fontconfig libraries it emulates its behaviour by running fontconfig cli utilities.

Therefore, nuking the matplotlib fontconfig cache so it discovers new fonts can be a lifesaver (the existence of this cache is direct proof of lack of complete fontconfig integration).

like image 20
nim Avatar answered Oct 11 '22 15:10

nim