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.
Install fonts on your system. Usually, double-click on the .ttf file and then click on the Install button in the window that pops up. Note that Matplotlib handles fonts in True Type Format (.ttf), so make sure you install fonts ending in .ttf. Clear matplotlib cache by running the following command on your terminal; rm -fr ~/.cache/matplotlib
Matplotlib can be installed using with the Anaconda Prompt. If the Anaconda Prompt is available on your machine, it can usually be seen in the Windows Start Menu. To install Matplotlib, open the Anaconda Prompt and type: After the installation is completed. Let’s start using Matplotlib with Jupyter Notebook.
Note that passing paths as strs is intentionally not supported, but you can simply wrap strs in pathlib.Paths as needed. Here, we use the Computer Modern roman font (cmr10) shipped with Matplotlib. For a more flexible solution, see Configuring the font familyand Fonts demo (object-oriented style).
Falling back to DejaVu Sans (prop.get_family (), self.defaultFamily [fontext])) you need to check whether matplotlib is “seeing” your custom font.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With