Google Colaboratory matplotlib图表中的自定义字体

时间:2018-08-12 16:52:51

标签: matplotlib fonts google-colaboratory

在本地matplotlib中使用自定义字体需要将.ttf s存储在matplotlib/mpl-data/fonts/ttf/文件夹中,然后调用mpl.font_manager._rebuild(),然后设置mpl.rcParams['font.sans-serif']

在Google Colaboratory中,似乎无法访问此ttf文件夹吗?

例如,我想使用Roboto font。安装后,将使用mpl.rcParams['font.sans-serif'] = 'Roboto'调用它。

3 个答案:

答案 0 :(得分:2)

ttf文件夹在这里:

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

因此,您要在此处下载ttf,例如:

!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')

答案 1 :(得分:2)

想要添加一个当前有效的完整、简洁的答案。

# 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')

注意,有几次这不能正常工作,并且没有显示请求的字体(即使没有显示错误或警告)。如果发生这种情况,请尝试出厂重置 Colab 运行时并再次运行。

答案 2 :(得分:1)

当发布matplotlib 3.2时,它将更加容易。

# For now we must upgrade to 3.2 rc first
# !pip install -U --pre matplotlib  
import matplotlib as mpl
mpl.font_manager.fontManager.addfont('thsarabunnew-webfont.ttf')
mpl.rc('font', family='TH Sarabun New')