我正在尝试在matplotlib中设置轴刻度的默认字体。目前我设置了字体路径:
path = 'palatino-regular.ttf'
prop = font_manager.FontProperties(fname=path)
对于每个图,我必须使用命令更改刻度字体:
for label in ax.get_xticklabels():
label.set_fontproperties(prop)
for label in ax.get_yticklabels():
label.set_fontproperties(prop)
有没有办法全局设置刻度字体,这样我就不必在本地为每个我绘制的图形提供这些命令。
可重现的代码
import numpy as np
import matplotlib.pyplot as plt
import itertools
import matplotlib.font_manager as font_manager
path = 'palatino-regular.ttf'
prop = font_manager.FontProperties(fname=path)
m = 5
n = 5
x = np.zeros(shape=(m, n))
plt.figure(figsize=(5.15, 5.15))
plt.clf()
plt.subplot(111)
marker = itertools.cycle(('o', 'v', '^', '<', '>', 's', '8', 'p'))
ax = plt.gca()
for i in range(1, n):
x = np.dot(i, [1, 1.1, 1.2, 1.3])
y = x ** 2
color = next(ax._get_lines.color_cycle)
plt.plot(x, y, linestyle='', markeredgecolor='none', marker=marker.next(), color=color, label = str(i))
plt.plot(x, y, linestyle='-', color = color)
plt.ylabel(r'y', labelpad=6)
plt.xlabel(r'x', labelpad=6)
for label in ax.get_xticklabels():
label.set_fontproperties(prop)
for label in ax.get_yticklabels():
label.set_fontproperties(prop)
plt.show()
我也尝试在matplotlibrc中设置字体,但是我收到以下错误:
/opt/share/python/v2.7.9.app/lib/python2.7/site-packages/matplotlib/font_manager.py:1236: UserWarning: findfont: Font family ['palatino-regular'] not found. Falling back to Bitstream Vera Sans
(prop.get_family(), self.defaultFamily[fontext]))