使用Pandas在循环中创建多个绘图?

2024-06-28 18:44:21 发布

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

我用jupyter笔记本画了一个条形图,我想画一个for循环中的熊猫图

这是我想要在for循环中绘制条形图的数据框

In[7]: test_df
    Lehi    Boise
1   True    True
2   True    True
3   False   False
4   True    True
5   True    True
6   True    True
7   True    True
8   False   False

我的代码

place = ['Lehi','Boise']
for p in place:
    bar = test_df.groupby(p).size().plot(kind='bar')

但我只得到“博伊西”条形图。。。 如果我把它们写在不同的jupyter单元格中,效果会很好

In[9]  bar = test_df.groupby('Lehi').size().plot(kind='bar')

In[10] bar = test_df.groupby('Boise').size().plot(kind='bar')

在jupyter笔记本中有没有解决这个问题的方法。 谢谢


Tags: intestfalsetruedfforsizeplot
1条回答
网友
1楼 · 发布于 2024-06-28 18:44:21

问题在于,如果没有额外的规范,循环将覆盖相同的打印轴。您可以更明确地在循环中为每个绘图创建一个新轴,并将df.plot映射到这些轴:

colors = ['red', 'green']
place = ['Lehi','Boise']
for p in place:
    fig, ax = plt.subplots(figsize=(5,5))
    bar = test_df.groupby(p).size().plot(kind='bar', color=colors, ax=ax)

这将在一个单元格下创建多个绘图。我包括了colors位的b/c,在您的原始Q中有类似的内容(未定义)。我相信groupby操作总是先对False进行排序,然后再对True进行排序,因此您只需按照您希望匹配的顺序呈现颜色

相关问题 更多 >