从数据Pandaseaborn python构建barplot x轴

2024-06-07 11:36:08 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我想用seaborn制作一个酒吧平面图。我的数据在表格中

Packet number,Flavour,Contents
1,orange,4
2,orange,3
3,orange,2
4,orange,4
...
36, orange,3
1, coffee,5
2, coffee,3
...
1, raisin,4
etc.

我的代码当前为:

^{pr2}$

我试着为每个包编号(在x轴上)创建条形图,在y轴上用每包的总含量除以每个条内的颜色。在

开始尝试计算每个数据包的总数

total_1 = (rd.loc[rd["Packet number"] == 1, "Contents"].sum())

但我不知道我该怎么做,或者是否有更简单的方法。在

任何建议都将不胜感激!在


Tags: 数据代码numberpacketcontentsetcrdseaborn
1条回答
网友
1楼 · 发布于 2024-06-07 11:36:08

您想使用hue来实现这一点。此外,当前您正在显示每个类别的平均值。要计算不同的函数,可以使用estimator。在

因此,您的代码应该是:

ax = sns.barplot(x="Packet number", y="Contents", hue="Flavour", data=rd)

或者如果您想显示总和而不是平均值:

^{pr2}$

编辑

如果您对堆积条形图感兴趣,可以直接使用pandas进行绘制,但需要首先对数据进行分组:

# Sum (or mean if you'd rather) the Contents per packet number and flavor
# unstack() will turn the flavor into columns, and fillna will put 0 in 
# all missing columns
grouped = rd.groupby(["Packet number", "Flavour"])["Contents"].sum().unstack().fillna(0)

# The x axis is taken from the index. The y axis from the columns
grouped.plot(kind="bar", stacked=True)

相关问题 更多 >

    热门问题