在写论文画图的时候,我们会对图片的标题,图例等文字部分设定规定好的字体和样式。
比如,我们给所有文字都设定好了Times New Roman字体,但是Times New Roman字体是一个比较特殊的存在,有两点
一个例子,我们使用plt画图,设置字体,应用字体
# 定义字体font1
font1 = {'family': 'Times New Roman',
'weight': 'normal',
'size': 10,
}
plt.figure(figsize=(8, 6))
epochs = range(0, len(tmodel_train))
A, = plt.plot(epochs, a, color="saddlebrown", linestyle="-", marker="o" , label='this is a ')
B, = plt.plot(epochs, b, color="mediumpurple", linestyle="-", marker="o" , label='this is b')
C, = plt.plot(epochs, c, color="dimgray", linestyle="-", marker="o" , label='this is c')
D, = plt.plot(epochs, d, color="y", linestyle="-", marker="o" , label='this is d')
# 将字体应用到图例上
legend = plt.legend(handles=[A,B,C,D], prop=font1)
# 画图
plt.xlabel('Epochs', font1)
plt.gca().set_ylim(0.85,1.0053)
plt.ylabel('Accuracy', font1)
plt.legend()
plt.savefig('demo.pdf')
结果是,图例的字体并不是我们想要的Times New Roman。即图片中字体不统一。
采用全局字体配置
将全局字体改为Times New Roman:
import matplotlib.pyplot as plt
plt.rc('font',family='Times New Roman')
在字体设置中,weight
负责字体的粗细。用默认的字体时,weight
的变化是可以改变字体粗细的。
但是一旦把字体设定为"Times New Roman",weight就没办法调节说明框中字体的粗细。默认使用Times New Roman的时候,字体会是加粗状态。这就是问题的所在,也是比较麻烦的一个地方。
解决方案是,添加一行语句:
del matplotlib.font_manager.weight_dict['roman']
matplotlib.font_manager._rebuild()
即可将Times New Roman字体变细。