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

Python保存Matplotlib子图异常:无标题轴编号仅黑底显示

问题排查与修复

核心错误1:代码缩进完全错误

你的循环体代码(从ax = axs[i]到设置轴属性的所有代码)没有缩进,导致for循环仅执行了break判断,循环结束后仅处理了最后一个索引对应的子图,其余子图根本没有被绘制。同时删除多余轴的代码也在循环外,会错误删除大量已创建的轴。

修复:将ax = axs[i]及之后的所有绘图代码缩进到for循环内部。

核心错误2:plt.show()后调用savefig

plt.show()会释放当前figure的资源,之后调用fig.savefig()会保存一个空的黑底图。需要将fig.savefig()移到plt.show()之前。

其他优化点

  • 简化标题处理的重复代码,合并i=5和i=6的重复逻辑
  • 删除未实际使用的num_plots变量

修复后的完整代码

indexes = pai_sum.index.tolist()
num_rows = 5
num_cols = 4
fig, axs = plt.subplots(num_rows, num_cols, figsize=(12, 15))
axs = axs.flatten()

for i, index in enumerate(indexes):
    # Break the loop if all indexes have been plotted
    if i == num_rows * num_cols:
        break
    
    ax = axs[i]

    # Extract the values for the current index
    values = pai_sum.loc[index].values
    columns = [f'{col}' for col in pai_sum.columns]

    bars = ax.bar(columns, values, color='lightgreen')

    # Set the title for the subplot with a number
    if i < 4:
        ax.set_title(f'{i+1}. {index}')
    elif i in (5, 6):
        title_parts = index.split('-')
        main_title = title_parts[0].strip()
        additional_info = title_parts[1].split('(')[1].strip(')')
        ax.set_title(f'{i+1}. {main_title} {additional_info}')
    else:
        truncated_title = index.split('-')[0].strip()
        ax.set_title(f'{i+1}. {truncated_title}')

    # Rotate x-axis labels for better readability
    ax.tick_params(axis='x', rotation=90)

    # Add the values inside the bars, rounding without decimals for the first 4 plots and plot 9
    if i < 4 or i == 12:
        for j, value in enumerate(values):
            ax.text(j, value, str(int(value)), ha='center', va='bottom')
    else:
        for j, value in enumerate(values):
            ax.text(j, value, str(round(value, 2)), ha='center', va='bottom')

    # Adjust the y-axis limits to provide more space above the bars
    ax.set_ylim(top=max(values) * 1.2)

# 删除未使用的子图,移到循环外执行
for j in range(i + 1, num_rows * num_cols):
    fig.delaxes(axs[j])

plt.tight_layout()
# 先保存再显示
fig.savefig('flagged.png')
plt.show()

修复说明

  1. 缩进修正后,循环会依次处理每个索引,绘制对应的子图并设置标题、轴标签等属性
  2. 将savefig移到show之前,确保保存的是完整的绘图结果
  3. 合并了i=5和i=6的标题处理逻辑,让代码更简洁
  4. 删除多余轴的代码移到循环外,避免重复执行

内容的提问来源于stack exchange,提问作者krisl

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 02:10:39