12

I am using Roboto Condensed font, which I downloaded on my laptop, for figures plotted with matplotlib. I am wondering if it is possible to import the font "on the fly", like CSS @import, from Google Fonts and use it straightforwardly with matplotlib.

I am using Jupyter notebook for python. There may be a way through it?

Best, F.

Flavien Lambert
  • 690
  • 1
  • 9
  • 22
  • https://stackoverflow.com/questions/7726852/how-to-use-a-random-otf-or-ttf-font-in-matplotlib – oz123 Jul 03 '17 at 13:00
  • 1
    What do you mean by "on the fly"? Do you wish to skip the download, and load directly from Google? – Shovalt Oct 15 '17 at 13:05

1 Answers1

5

You can get .ttf files from the google 'fonts' repo on github. You can select a font from the list there, and find a link to the .ttf file. For example, if you go into the 'alike' directory, you'll find a file named 'Alike-Regular.ttf', whose URL is: https://github.com/google/fonts/blob/master/ofl/alike/Alike-Regular.ttf .

Once you find your font, you can use the following snippet to load it into matplotlib "on the fly", using a temporary file:

from tempfile import NamedTemporaryFile
import urllib2
import matplotlib.font_manager as fm
import matplotlib.pyplot as plt

github_url = 'https://github.com/google/fonts/blob/master/ofl/alike/Alike-Regular.ttf'

url = github_url + '?raw=true'  # You want the actual file, not some html

response = urllib2.urlopen(url)
f = NamedTemporaryFile(delete=False, suffix='.ttf')
f.write(response.read())
f.close()

fig, ax = plt.subplots()
ax.plot([1, 2, 3])

prop = fm.FontProperties(fname=f.name)
ax.set_title('this is a special font:\n%s' % github_url, fontproperties=prop)
ax.set_xlabel('This is the default font')

plt.show()

Result:

Plot with custom google font

Shovalt
  • 6,407
  • 2
  • 36
  • 51