来自pandas datafram的多个条形图

2024-06-01 14:40:19 发布

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

所以我有一个像

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”中,而不是在任何其他位置),则将其他位置的“peach”替换为零。在


Tags: 项目name名称appleindexfoo颜色bar
1条回答
网友
1楼 · 发布于 2024-06-01 14:40:19

我复制/粘贴你的数据到一个名为'测试.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

如果你真的想通过颜色区分“index”(我称之为“status”),你可以定义一个新变量,它将“exp_name”与“status”结合起来

^{pr2}$

像这样的东西

enter image description here

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

相关问题 更多 >