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

如何用Pandas按字符串标签分组绘制总价柱状图?

解决多图表问题并生成正确的总价柱状图

咱们先拆解下问题根源:你用df_new.groupby([df_new.type]).plot()的时候,pandas会默认为每个分组单独生成一个图表,这就是为啥你会看到一堆图弹出来。要实现按type展示总价的需求,得先把数据做聚合计算,再基于汇总后的数据绘图才行。

步骤1:先整理数据并计算每个type的总价

先把你的原始数据转换成DataFrame,再分组求和得到每个品类的总价:

import pandas as pd
import matplotlib.pyplot as plt

# 把你提供的原始数据整理成DataFrame
raw_data = [
    ["cookie", 1],
    ["cookie", 3],
    ["brownie", 2],
    ["candy", 4],
    ["brownie", 4]
]
df_new = pd.DataFrame(raw_data, columns=["type", "price"])

# 分组计算每个type的总价,重置索引方便后续绘图
type_totals = df_new.groupby("type")["price"].sum().reset_index()

步骤2:绘制单一柱状图并添加百分比标签

基于聚合后的type_totals绘图,这样只会生成一个图表,再把你需要的百分比标签加上:

plt.figure(figsize=(18,7))
# 指定x轴为type,y轴为汇总后的price,同时指定ax避免生成多图
ax2 = type_totals.plot(
    kind='bar',
    x='type',
    y='price',
    color="green",
    fontsize=13,
    legend=False,
    ax=plt.gca()
)

# 设置图表标题和坐标轴标签
ax2.set_title("Totals", fontsize=18)
ax2.set_ylabel("Total Price", fontsize=18)
ax2.set_xlabel("Type", fontsize=18)

# 计算所有品类的总价,用于百分比计算
total = type_totals["price"].sum()

# 为每个柱子添加百分比标签
for i in ax2.patches:
    height = i.get_height()
    ax2.text(
        i.get_x() + i.get_width()/2,  # 水平居中对齐
        height + 0.2,  # 垂直方向稍微上移,避免和柱子重叠
        f"{round((height/total)*100, 2)}%",
        fontsize=15,
        color='black',
        ha='center'
    )

plt.tight_layout()
plt.show()

原代码问题解析

groupby().plot()的设计初衷是方便查看每个分组的细节数据,所以会为每个type单独生成图表,但这和你要展示「分组汇总后对比」的需求不匹配。先聚合再绘图,就能完美解决多图表的问题,同时精准展示每个品类的总价占比。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:27:20