python中设置字体常用有两种方式,一种是导入fontmanager,一种是直接写fontdict,个人喜欢第二种,比较方便,但对中文支持不好,如需中文,最好是第一种,废话不多说,详细代码如下,第一种代码详见第2/16/49行,第二种详见第18/41/42行, excel中我随意写了一些数据:
from matplotlib import pyplot as plt import matplotlib.font_manager as fm import numpy as np import pandas as pd def draw_bar(ax, x, y1, y2, y3, width=0.3): labels = ['C$_1$', 'C$_2$', 'C$_3$'] differential = [-1, 0, 1] # color = plt.get_cmap('inferno')(np.linspace(0.15, 0.85, 3)) ax.bar(x + width*differential[0], y1, width=width, color='#ff4373', label=labels[0]) ax.bar(x + width*differential[1], y2, width=width, color='#1687a7', label=labels[1]) ax.bar(x + width*differential[2], y3, width=width, color='#5be7c4', label=labels[2]) return ax my_font = fm.FontProperties(fname=r'C:\Windows\Fonts\Arial.ttf') font1 = {'family': 'Times New Roman', 'weight': 'bold', 'size': 12, 'style':'italic'} excel = pd.read_excel('Table_data.xlsx', sheet_name='B') excel = np.array(excel) title = ['0%', '10%', '20%', '30%', '40%', '50%', '60%'] A_1 = excel[17][2:] A_2 = excel[18][2:] A_3 = excel[19][2:] B_1 = excel[20][2:] B_2 = excel[21][2:] B_3 = excel[22][2:] C_1 = excel[23][2:] C_2 = excel[24][2:] C_3 = excel[25][2:] fig, ax = plt.subplots(1, 3, figsize=(12, 4)) width = 0.25 index = np.arange(len(title)) ax1 = draw_bar(ax[0], index, A_1, A_2, A_3, width=width) ax2 = draw_bar(ax[1], index, B_1, B_2, B_3, width=width) ax3 = draw_bar(ax[2], index, C_1, C_2, C_3, width=width) for i in [ax1, ax2, ax3]: i.set_xticks(ticks=index) i.set_xticklabels(labels=title) i.set_xlabel('H$_2$ content') i.legend() ax1.set_ylabel('Yield 1 (%)', fontdict={'fontproperties':my_font}) ax2.set_ylabel('Yield 2 (g/h)', fontdict=font1) ax3.set_ylabel('Yield 2 (g/m$^2$/h)', fontdict=font1) plt.tight_layout() plt.savefig('94.tif', dpi=300) plt.show()图片如下: