通过仅导入 pandas 在 for 循环中实现多重绘图

问题描述 投票:0回答:1

有时,

DataFrame.plot()
循环内的
for
会生成多个图表。

import pandas as pd

data = {'Str': ['A', 'A', 'B', 'B'], 'Num': [i for i in range(4)]}
df = pd.DataFrame(data)
for n in ['A', 'B']:
  df[df.Str == n].plot(kind='bar')

enter image description here

但有时,它会生成单个图表。

import pandas as pd

data = {'C1': ['A', 'A', 'B', 'B'], 
        'C2': [i for i in range(4)],
        'C3': [1,2,1,2]}
df = pd.DataFrame(data)
for n in [1,2]:
  df[df.C3 == n].groupby('C1').C2.sum().plot(kind='bar')

enter image description here

从前面的代码来看,如果

plt.show()
被添加到循环末尾。它将生成多个图表。

import pandas as pd
import matplotlib.pyplot as plt


data = {'C1': ['A', 'A', 'B', 'B'], 
        'C2': [i for i in range(4)],
        'C3': [1,2,1,2]}
df = pd.DataFrame(data)
for n in [1,2]:
  df[df.C3 == n].groupby('C1').C2.sum().plot(kind='bar')
  plt.show()

enter image description here

我不想使用

plt.show()
。实际上我只想
import
pandas
并使用
for
循环创建多个图表。

pandas
1个回答
0
投票

如果您不想要

import matplotlib
import seaborn
,请将结果写入数据框并使用
plot
函数和
subplots=True

df.groupby(['C3', 'C1'])['C2'].sum().unstack(0).plot(kind='bar', subplots=True)

enter image description here

但是,如果我是你,我可能会使用

matplotlib
seaborn
,除非有特殊情况阻止你安装这些库。

© www.soinside.com 2019 - 2024. All rights reserved.