如何在matplotlib中使用(随机)*.otf或*.ttf字体?

2024-05-15 21:44:47 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在计算机上的字体库中使用任何类型的字体(例如*otf*ttf)在所有matplotlib图形中使用?


Tags: 图形类型matplotlib计算机字体ttf字体库otf
3条回答

在*nix上,通过启用matplotlib的fontconfig后端,可以使用所有系统字体。

但是matplotlib并没有真正与fontconfig库对话,而是通过运行fontconfig cli实用程序来模拟其行为。

因此,轻推matplotlib fontconfig缓存,以便它发现新字体可能是一个救命稻草(此缓存的存在直接证明了缺乏完整的fontconfig集成)。

请看下面的示例:http://matplotlib.sourceforge.net/examples/api/font_file.html

一般来说,如果您想使用特定的.ttf文件,您应该这样做。(请记住,指向特定的字体文件通常是个坏主意!)

import matplotlib.font_manager as fm
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(range(10))

prop = fm.FontProperties(fname='/usr/share/fonts/truetype/groovygh.ttf')
ax.set_title('This is some random font', fontproperties=prop, size=32)

plt.show()

enter image description here

通常,您只需指向字体的名称,让matplotlib担心找到特定的文件。E、 g

import matplotlib.pyplot as plt

plt.plot(range(10))
plt.title('This is some random font', family='GroovyGhosties', size=32)

plt.show()

如果希望matplotlib始终使用特定字体,则customize your ^{} file。(font.family是您想要设置的。请注意,您应该指定字体的名称,而不是指定.ttf文件的路径。)

作为动态执行此操作的示例(即,不设置特定的.matplotlibrc文件):

import matplotlib as mpl
mpl.rcParams['font.family'] = 'GroovyGhosties'

import matplotlib.pyplot as plt

plt.plot(range(10))
plt.title('Everything is crazy!!!', size=32)
plt.show()

enter image description here

您也可以在matplot config中指定字体并覆盖默认字体系列,例如对于*nix

~/.matplotlib/matplotlibrc

font.family: sans-serif
font.sans-serif: your font,sans-serif

相关问题 更多 >