【问题标题】:Can I load Google fonts with Matplotlib and Jupyter?我可以使用 Matplotlib 和 Jupyter 加载 Google 字体吗?
【发布时间】:2016-01-08 18:58:31
【问题描述】:

我正在使用我在笔记本电脑上下载的 Roboto Condensed 字体,用于使用 matplotlib 绘制的图形。我想知道是否可以从 Google 字体“即时”导入字体,如 CSS @import,并直接与 matplotlib 一起使用。

我正在为 python 使用 Jupyter 笔记本。有办法通过吗?

最好, F.

【问题讨论】:

标签: matplotlib ipython-notebook google-font-api jupyter


【解决方案1】:

您可以从github 上的 google 'fonts' repo 获取 .ttf 文件。您可以从那里的列表中选择一种字体,然后找到指向 .ttf 文件的链接。例如,如果你进入 'alike' 目录,你会发现一个名为 'Alike-Regular.ttf' 的文件,其 URL 为:https://github.com/google/fonts/blob/master/ofl/alike/Alike-Regular.ttf

找到字体后,您可以使用以下 sn-p 使用临时文件“即时”将其加载到 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()

结果:

【讨论】:

    猜你喜欢
    • 2017-01-18
    • 2019-05-04
    • 2011-10-16
    • 2014-10-26
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    • 2017-10-08
    • 2021-04-02
    相关资源
    最近更新 更多