首页 > 解决方案 > 使用熊猫在循环中创建多图?

问题描述

我正在使用 jupyter notebook 绘制条形图,并且我想在 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 notebook 中有什么解决方案可以解决这个问题。谢谢!

标签: pythonpandasmatplotlibseaborn

解决方案


问题是如果没有额外的规范,循环会覆盖相同的绘图轴。您可以在循环中为每个绘图更明确地创建一个新轴,并映射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,所以你只需要按照你想要匹配的顺序呈现颜色。


推荐阅读