gpt4 book ai didi

python - pandas 数据框中的多个条形图

转载 作者:行者123 更新时间:2023-12-02 05:05:01 25 4
gpt4 key购买 nike

所以我有一个像这样的数据框

exp_name, index, items, clicks
"foo",0, "apple",200
"foo",0, "banana", 300
"foo",0,"melon",220
"foo",1, "apple", 10
"foo",1,"peach", 20
"bar",0, "apple",400
"bar",0,'banana', 500
"bar",0, "melon",240
"bar",1,"apple",500

等等

我想为每个实验名称绘制...每个索引中每个项目的点击次数条形图,但按索引着色。所以基本上..图 1.. 对于实验“foo”,条形图.. 其中索引 == 0.. 索引 0 的所有条形图采用一种颜色。索引 1 的所有条形图采用另一种颜色。

如果该项目丢失(例如 peach 在“foo”中,1 但不在任何其他地方),请将其他地方的“peach”替换为 0。

最佳答案

我将您的数据复制/粘贴到名为“test.txt”的 txt 文件中,并将“index”重命名为“status”,以避免与 DataFrame 索引混淆。然后我使用Seaborn库来根据您提到的意外情况制作条形图(据我所知)。我使用子图而不是使用颜色来分隔“状态”,因为我个人认为它看起来更干净,但我使用下面的颜色,因为这就是您所问的。

import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt

df = pd.read_csv('test.txt')
fig, ax = sns.plt.subplots(1, 1, figsize=(7,5))
sns.factorplot(x="items", y="clicks", hue="exp_name", col="status", data=df, kind="bar")
plt.show()

给出以下内容:enter image description here

如果您确实想通过颜色区分“索引”(我称之为“状态”),您可以定义一个将“exp_name”与“状态”组合在一起的新变量

df['exp'] = df.exp_name + df.status.astype(str)
sns.factorplot(x="items", y="clicks", hue="exp", data=df, kind="bar")

给出类似这样的东西

enter image description here

查看 seaborn 的文档如果您还有更多问题。这是一个非常棒的分类数据库。更改图例标签和其他设置遵循 matplotlib 约定。

关于python - pandas 数据框中的多个条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37955881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com