从数据 pandas seaborn python 构建 barplot x 轴

barplot x axis construction from data pandas seaborn 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.

我的代码目前是:

revels_data = pd.read_csv("testtt.txt") rd = revels_data

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

我正在尝试为每个数据包编号(在 x 轴上)创建条形图,这些条形图在每个条形图内按口味划分,每个数据包的总含量在 y 轴上。

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

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

但不确定我将如何从那里开始,或者是否有更简单的方法。

非常感谢任何建议!

您想为此使用 hue。此外,目前您正在显示每个类别的平均值。要计算不同的函数,您可以使用 estimator.

因此,您的代码应该是:

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

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

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

编辑:

如果您对堆叠条形图感兴趣,可以直接使用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)