Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom fonts in Google Colaboratory matplotlib charts

Using custom fonts in matplotlib locally involves storing the .ttfs in the matplotlib/mpl-data/fonts/ttf/ folder, then calling mpl.font_manager._rebuild(), then setting mpl.rcParams['font.sans-serif'].

Is there any way to do this in Google Colaboratory, where it doesn't seem that this ttf folder is accessible?

For example, I'd like to use the Roboto font. After installing, this would be invoked using mpl.rcParams['font.sans-serif'] = 'Roboto'.

like image 390
Max Ghenis Avatar asked Dec 18 '22 21:12

Max Ghenis


2 Answers

The ttf folder is here:

/usr/local/lib/python3.6/dist-packages/matplotlib/mpl-data/fonts/ttf

So you want to download the ttf there, e.g.:

!wget https://github.com/Phonbopit/sarabun-webfont/raw/master/fonts/thsarabunnew-webfont.ttf -P /usr/local/lib/python3.6/dist-packages/matplotlib/mpl-data/fonts/ttf

matplotlib.font_manager._rebuild()
matplotlib.rc('font', family='TH Sarabun New')

update 2019-12

_rebuild() no longer works. Here's another method which still works.

import matplotlib
import matplotlib.font_manager as fm

!wget https://github.com/Phonbopit/sarabun-webfont/raw/master/fonts/thsarabunnew-webfont.ttf
fm.fontManager.ttflist += fm.createFontList(['thsarabunnew-webfont.ttf'])
matplotlib.rc('font', family='TH Sarabun New')
like image 93
korakot Avatar answered Jan 01 '23 10:01

korakot


Wanted to add a full, succinct answer that currently works.

# Download fonts of choice. Here we download Open Sans variants to
# the current directory.
# It's not necessary to download to the share or matplotlib folders:
# /usr/share/fonts/truetype
# /usr/local/lib/python3.6/dist-packages/matplotlib/mpl-data/fonts/ttf
!wget 'https://github.com/google/fonts/raw/master/apache/opensans/OpenSans-Regular.ttf'
!wget 'https://github.com/google/fonts/raw/master/apache/opensans/OpenSans-Light.ttf'
!wget 'https://github.com/google/fonts/raw/master/apache/opensans/OpenSans-SemiBold.ttf'
!wget 'https://github.com/google/fonts/raw/master/apache/opensans/OpenSans-Bold.ttf'
from matplotlib import font_manager as fm, pyplot as plt

# Pick up any fonts in the current directory.
# If you do end up downloading the fonts to /usr/share/fonts/truetype,
# change this to: fm.findSystemFonts()
font_files = fm.findSystemFonts('.')

# Go through and add each to Matplotlib's font cache.
for font_file in font_files:
    fm.fontManager.addfont(font_file)

# Use your new font on all your plots.
plt.rc('font', family='Open Sans')

Note, a few times this didn't work properly and the requested font wasn't displayed (even though no error or warning was shown). If that happens, try factory resetting your Colab runtime and running again.

like image 42
getup8 Avatar answered Jan 01 '23 10:01

getup8