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

循环生成柱状图时添加百分比变化标签,解决冗余图表问题

解决方案

问题根源

你当前代码的核心问题是使用了嵌套循环,两次遍历DataFrame的列,导致生成的图表数量是列数的平方(比如有n列就会生成n×n幅图),完全超出需求。而实际上timeframe和timeframe1的列名完全一致(akp是ak计算百分比变化得到的),只需要一次循环就能完成对应数据的匹配。

修正后的代码

ak = ak.set_index("combo")
ak = ak.T
akp = ak.pct_change()
colors = ['blue', 'blue','blue', 'blue', 'blue', 'red', 'red', 'red' ]
timeframe = ak["2019":"2026"]
timeframe1 = akp["2019":"2026"]

# 仅需一层循环遍历列名
for col in timeframe.columns:
    plt.figure()
    # 用同一列名获取数值数据绘制柱状图
    barplot = plt.bar(timeframe.index, timeframe[col], color=colors)
    plt.grid(False)
    plt.ylabel('A')
    # 用同一列名获取百分比变化数据作为标签
    plt.bar_label(barplot, labels=round(timeframe1[col], 2), label_type="edge")
    # 可选:添加标题区分不同列的图表
    plt.title(f'数据列:{col}')

# 显示所有生成的图表
plt.show()

关键修改说明

  • 移除内层循环,仅遍历一次列名,确保每列对应生成一幅图
  • 用统一的循环变量col同时索引timeframe和timeframe1,保证数值数据与百分比标签一一对应
  • 新增标题(可选),方便快速识别不同列对应的图表
  • 添加plt.show()确保所有图表正常显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 11:37:58