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

为Matplotlib直方图子图添加图标题与坐标轴标题报错求助

问题分析与解决

错误原因

使用plt.subplots(2, 3)创建子图时,返回的axes是2行3列的NumPy数组,并非单个Axes对象。直接调用axes.set_xlabel()或axes.set_ylabel()会报错,因为数组本身没有这些方法,必须针对数组中的每个子图(单个Axes对象)调用对应方法。

修正方案

以下两种方式可实现为每个子图添加单独的坐标轴标签和标题:

方法1:逐个指定子图设置

直接通过子图索引(如axes[0,0])调用set_xlabel()、set_ylabel()和set_title():

import matplotlib.pyplot as plt
import pandas as pd

uid_df = pd.read_excel('myexcel.xlsx', sheet_name='UID')
sid_df = pd.read_excel('myexcel.xlsx', sheet_name='SID')

fig, axes = plt.subplots(2, 3, figsize=(12, 8))  # 可选:调整画布尺寸避免标签重叠

# 第一行子图配置
uid_df.hist('Ass1', ax=axes[0,0], color="blue", bins=20)
axes[0,0].set_xlabel('分数')
axes[0,0].set_ylabel('人数')
axes[0,0].set_title('UID组-作业1分数分布')

uid_df.hist('Ass2', ax=axes[0,1], color="green", bins=20)
axes[0,1].set_xlabel('分数')
axes[0,1].set_ylabel('人数')
axes[0,1].set_title('UID组-作业2分数分布')

uid_df.hist('FE', ax=axes[0,2], color="red", bins=20)
axes[0,2].set_xlabel('分数')
axes[0,2].set_ylabel('人数')
axes[0,2].set_title('UID组-期末分数分布')

# 第二行子图配置
sid_df.hist('Ass1', ax=axes[1,0], color="blue", bins=20)
axes[1,0].set_xlabel('分数')
axes[1,0].set_ylabel('人数')
axes[1,0].set_title('SID组-作业1分数分布')

sid_df.hist('Ass2', ax=axes[1,1], color="green", bins=20)
axes[1,1].set_xlabel('分数')
axes[1,1].set_ylabel('人数')
axes[1,1].set_title('SID组-作业2分数分布')

sid_df.hist('FE', ax=axes[1,2], color="red", bins=20)
axes[1,2].set_xlabel('分数')
axes[1,2].set_ylabel('人数')
axes[1,2].set_title('SID组-期末分数分布')

plt.tight_layout()  # 自动调整子图间距,避免元素重叠
plt.show()

方法2:遍历子图批量设置(适合规律化标签)

如果子图的标题、数据列有规律,可通过axes.flat将二维数组展平为一维,批量遍历处理:

import matplotlib.pyplot as plt
import pandas as pd

uid_df = pd.read_excel('myexcel.xlsx', sheet_name='UID')
sid_df = pd.read_excel('myexcel.xlsx', sheet_name='SID')

fig, axes = plt.subplots(2, 3, figsize=(12, 8))

# 定义子图的标题、数据源、目标列、颜色
plot_configs = [
    ('UID组-作业1分数分布', uid_df, 'Ass1', 'blue'),
    ('UID组-作业2分数分布', uid_df, 'Ass2', 'green'),
    ('UID组-期末分数分布', uid_df, 'FE', 'red'),
    ('SID组-作业1分数分布', sid_df, 'Ass1', 'blue'),
    ('SID组-作业2分数分布', sid_df, 'Ass2', 'green'),
    ('SID组-期末分数分布', sid_df, 'FE', 'red'),
]

# 遍历展平后的子图与配置信息
for ax, (title, df, col, color) in zip(axes.flat, plot_configs):
    df.hist(col, ax=ax, color=color, bins=20)
    ax.set_xlabel('分数')
    ax.set_ylabel('人数')
    ax.set_title(title)

plt.tight_layout()
plt.show()

额外提示

  • plt.tight_layout()是避免子图元素重叠的实用工具,建议添加。
  • 若需要全局统一的坐标轴标签,可使用fig.supxlabel()和fig.supylabel(),再配合子图的单独标题使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:40:33