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

使用df.plot.bar()绘制柱状图显示异常,请求排查问题

柱状图绘制异常排查求助

我编写了如下代码,尝试遍历DataFrame的指定列(变量列表见代码)并循环绘制柱状图。以newerdf['age']列为例,该列取值1、2、3分别对应男、女、其他,预期生成3个柱状条,但实际生成的图表不符合预期。附上代码、数据示例及图表说明,恳请帮忙排查错误原因!

代码

listedvariables = ['age','gender-quantised','hours_of_sleep','frequency_of_alarm_usage','nap_duration_mins','frequency_of_naps','takes_naps_yes/no','highest_education_level_acheived','hours_exercise_per_week_in_last_6_months','drink_alcohol_yes/no','drink_caffeine_yes/no','hours_exercise_per_week','hours_of_phone_use_per_week','video_game_phone/tablet_hours_per_week','video_game_all_devices_hours_per_week']
for i in range(0,len(listedvariables)): 
    fig = newerdf[[listedvariables[i]]].plot.bar(figsize=(30,20))
    fig.tick_params(axis='x',labelsize=40)
    fig.tick_params(axis='y',labelsize=40)
    plt.tight_layout()

数据示例(newerdf['age'])

age
0   2
1   2
2   4
3   3
5   2
... ...
911 2
912 1
913 2
914 3
915 2

图表说明

当前生成的图表将每一行数据作为独立柱状条展示,x轴为DataFrame的行索引,而非按age的不同取值分组统计后的结果,完全不符合预期的分组柱状图效果。


问题原因及解决方案

错误原因

直接对单列DataFrame调用plot.bar()时,默认会把每一行的索引作为x轴、每行的数值作为y轴,所以会生成数百个柱状条,而非按取值分组统计后的结果。必须先对列的取值做频数统计,再基于统计结果绘制柱状图。

修正后的代码

import matplotlib.pyplot as plt

listedvariables = ['age','gender-quantised','hours_of_sleep','frequency_of_alarm_usage','nap_duration_mins','frequency_of_naps','takes_naps_yes/no','highest_education_level_acheived','hours_exercise_per_week_in_last_6_months','drink_alcohol_yes/no','drink_caffeine_yes/no','hours_exercise_per_week','hours_of_phone_use_per_week','video_game_phone/tablet_hours_per_week','video_game_all_devices_hours_per_week']

for var in listedvariables: 
    # 统计列中各取值的出现频数,并按取值排序
    value_counts = newerdf[var].value_counts().sort_index()
    # 基于频数统计结果绘制柱状图
    fig = value_counts.plot.bar(figsize=(30,20))
    fig.tick_params(axis='x',labelsize=40)
    fig.tick_params(axis='y',labelsize=40)
    # 添加图表标题,方便区分不同变量
    fig.set_title(f'{var} 分布情况', fontsize=45)
    plt.tight_layout()
    # 若需保存图表,可取消下方注释
    # plt.savefig(f'{var}_distribution.png')
    plt.show()

关键改动说明

  1. 用value_counts()统计每个变量不同取值的出现次数,sort_index()保证x轴按取值大小有序排列(比如age的1、2、3顺序)
  2. 直接对频数统计结果调用plot.bar(),此时x轴为变量的不同取值,y轴为对应频数,完全符合预期
  3. 循环时直接遍历变量列表,比用range索引更简洁易读
  4. 添加标题,方便快速区分不同变量的图表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 19:55:17