You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib设置yticks字号时出现部分刻度字号不一致异常

Matplotlib y轴刻度字号不一致问题解决

问题根因

你在设置y轴刻度字号前调用了plt.tight_layout(),该方法会触发Matplotlib自动生成默认y轴刻度并套用全局默认字号,后续执行plt.yticks(fontsize=6)时仅能覆盖部分手动指定的刻度,未被覆盖的刻度就会出现字号偏大的情况。

修复方案

方案1:调整代码执行顺序

将plt.tight_layout()移动到所有刻度、图例、标签配置完成之后,plt.savefig()之前即可,修改后的完整代码如下:

def mm_to_inch(value):
    return value/25.4

import matplotlib
matplotlib.use('Agg')
matplotlib.rcParams['font.sans-serif'] = "Arial"
matplotlib.rcParams['font.family'] = "sans-serif"
matplotlib.rcParams['figure.dpi'] = 300
import pandas as pd
import matplotlib.pyplot as plt

size = 112
fig, ax1 = plt.subplots(figsize=(mm_to_inch(size), mm_to_inch(size/2)))

df = pd.read_csv('testing_errors_prob.csv')
df = df.drop(['precision', 'recall', 'TP', 'FP', 'TN', 'FN'], axis=1)
df = df.sort_values(by=['accuracy'], ascending=False)
df = df.replace({'Gaussian Nb': 'Gaussian\nNb', 'Extra Trees': 'Extra\nTrees', 'Random Forest': 'Random\nForest',
                     'Decision Tree': 'Decision\nTree', 'Gradient Boost': 'Gradient\nBoost', 'Linear SVC': 'Linear\nSVC',
                     'Ada Boost': 'Ada\nBoost', 'Bernouli Nb': 'Bernouli\nNb'})
df.plot.bar(x='model', ax=ax1, color=['#093145', '#107896', '#829356'], width=0.8)

plt.xticks(rotation=45, ha="right", fontsize=6)
plt.yticks(fontsize=6)
plt.legend(["Accuracy", "F1", "AUC ROC"], prop={'size': 5})

plt.subplots_adjust(left=0.07, right=0.9, top=0.9, bottom=0.2)
plt.xlabel('')
plt.tight_layout()

plt.savefig('results_updateddd_{}.png'.format(size))
plt.savefig('results_updateddd_{}.pdf'.format(size))
plt.close()

注:原代码中legend参数同时写了fontsize="xx-large"和prop={'size':5}属于冗余配置,已删除无效的fontsize="xx-large"参数避免样式冲突。

方案2:强制统一所有刻度字号

如果调整顺序后仍有异常,可以直接遍历y轴所有刻度标签单独设置字号,确保100%覆盖所有刻度,在plt.yticks(fontsize=6)之后添加以下代码即可:

for label in ax1.get_yticklabels():
    label.set_fontsize(6)

内容的提问来源于stack exchange,提问作者Perl Del Rey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 18:57:01