唷,我把它写在 100 行以下,@nim 这也更详细地解释了它是多么危险,一些修改完全改变了字体属性和字体大小的行为。
先决条件:Matplotlib 和包含 ttf 字体文件 calibri.ttf 的脚本同级字体文件夹
但这就是我为你准备的复活节彩蛋:
import os
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
from matplotlib import ft2font
from matplotlib.font_manager import ttfFontProperty
__font_dir__ = os.path.join(os.path.dirname(__file__),"font")
fpath = os.path.join(__font_dir__,'calibri.ttf')
font = ft2font.FT2Font(fpath)
fprop = fm.FontProperties(fname=fpath)
ttfFontProp = ttfFontProperty(font)
fontsize=18
fontprop = fm.FontProperties(family='sans-serif',
#name=ap.fontprop.name,
fname=ttfFontProp.fname,
size=fontsize,
stretch=ttfFontProp.stretch,
style=ttfFontProp.style,
variant=ttfFontProp.variant,
weight=ttfFontProp.weight)
matplotlib.rcParams.update({'font.size': fontsize,
'font.family': 'sans-serif'})
fig, axis = plt.subplots()
axis.set_title('Text in a cool font',fontsize=fontsize,fontproperties=fontprop)
ax_right = axis.twinx()
axis.set_xlabel("some Unit",fontsize=fontsize,fontproperties=fontprop)
leftAxesName,rightAxesName = "left Unit", "right Unit"
axis.set_ylabel(leftAxesName,fontsize=fontsize,fontproperties=fontprop)
if rightAxesName:
ax_right.set_ylabel(rightAxesName,fontsize=fontsize,fontproperties=fontprop)
for xLabel in axis.get_xticklabels():
xLabel.set_fontproperties(fontprop)
xLabel.set_fontsize(fontsize)
for yLabel in axis.get_yticklabels():
yLabel.set_fontproperties(fontprop)
yLabel.set_fontsize(fontsize)
yTickLabelLeft = ax_right.get_yticklabels()
for yLabel in yTickLabelLeft:
yLabel.set_fontproperties(fontprop)
yLabel.set_fontsize(fontsize)
axis.plot([0,1],[0,1],label="test")
nrow,ncol=1,1
handels,labels= axis.get_legend_handles_labels()
propsLeft=axis.properties()
propsRight=ax_right.properties()
print(propsLeft['title'],propsLeft['xlabel'],propsLeft['ylabel'])
print(propsRight['ylabel'])
fig.set_tight_layout({'rect': [0, 0, 1, 0.95], 'pad': 0.05, 'h_pad': 1.5})
fig.tight_layout()
fig.set_alpha(True)
leg_fig = plt.figure()
leg = leg_fig.legend(handels, labels, #labels = tuple(bar_names)
ncol=ncol, mode=None,
borderaxespad=0.,
loc='center', # the location of the legend handles
handleheight=None, # the height of the legend handles
#fontsize=9, # prop beats fontsize
markerscale=None,
frameon=False,
prop=fontprop)
plt.show()