我可以使用Matplotlib和Jupyter加载Google字体吗?

Fla*_*ert 9 matplotlib google-font-api ipython-notebook jupyter

我正在使用我在笔记本电脑上下载的Roboto Condensed字体,用于使用matplotlib绘制的数字.我想知道是否有可能从谷歌字体"即时"导入字体,如CSS @import,并直接使用它与matplotlib.

我正在使用Jupyter笔记本进行python.有可能通过它吗?

最好的,F.

Sho*_*alt 5

您可以从github上的 google 'fonts' 存储库获取 .ttf 文件。您可以从列表中选择一种字体,然后找到 .ttf 文件的链接。例如,如果您进入“alike”目录,您将找到一个名为“Alike-Regular.ttf”的文件,其 URL 为: https: //github.com/google/fonts/blob/master/ofl/相似/相似-Regular.ttf

找到字体后,您可以使用以下代码片段使用临时文件“即时”将其加载到 matplotlib 中:

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()
Run Code Online (Sandbox Code Playgroud)

结果:

使用自定义谷歌字体绘制