python - 使用熊猫在循环中创建多图?
问题描述
我正在使用 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 中有什么解决方案可以解决这个问题。谢谢!
解决方案
问题是如果没有额外的规范,循环会覆盖相同的绘图轴。您可以在循环中为每个绘图更明确地创建一个新轴,并映射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
,所以你只需要按照你想要匹配的顺序呈现颜色。
推荐阅读
- python - 我想为 pd.groupby.max() 函数返回的值返回原始 df 索引
- javascript - 团队主动消息和图形 API 令牌
- r - R中的ggplot2:为什么箱形图填充颜色很苍白?
- spring - Spring Kafka bean 配置 - 为什么调用 bean 方法而不是 autowire?
- javascript - 限制 Javascript 执行数量 +/-
- discord - discord.py 上的意外缩进
- r - dplyr 可以从 as.character 字符串中删除所有点吗?
- java - 如何将同义词添加到 Java 中的 switch 语句?
- package - 当 nuget.config 中的自定义包文件夹时,repositoryPath 不起作用
- javascript - Animate.css 承诺有时不会在动画结束后清理类