在 Python 的 Matplotlib 中调整字体和图例位置,可按如下方式操作:
1. 全局设置 Times New Roman 字体
import matplotlib.pyplot as plt# 设置全局字体为 Times New Roman
plt.rcParams['font.family'] = 'serif' # 主字体族
plt.rcParams['font.serif'] = ['Times New Roman'] # 具体指定衬线字体为 Times New Roman
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示异常问题
2. 单独设置 x 轴标签字体
# 方法 1:通过 fontdict 参数直接设置
plt.xlabel('Step', fontdict={'family': 'Times New Roman', 'size': 12})# 方法 2:通过对象属性设置
ax = plt.gca()
ax.xaxis.label.set_fontname('Times New Roman')
ax.xaxis.label.set_size(12)
3. 调整图例位置
# 显示图例并指定位置(常见位置参数)
plt.legend(loc='upper right') # 右上角
# plt.legend(loc='lower left') # 左下角
# plt.legend(loc='best') # 自动选择最佳位置# 更精细的位置控制(使用 bbox_to_anchor)
plt.legend(bbox_to_anchor=(0.5, 1.05), loc='center') # 图例居中显示在图像上方