Python 使用for loop from dataframe创建多个绘图

Python 使用for loop from dataframe创建多个绘图,python,python-3.x,matplotlib,Python,Python 3.x,Matplotlib,我试图创建一个包含9个子图(3 x 3)的图形。十、 Y轴数据来自使用groupby的数据帧。这是我的密码: fig, axs = plt.subplots(3,3) for index,cause in enumerate(cause_list): df[df['CAT']==cause].groupby('RYQ')['NO_CONSUMERS'].mean().axs[index].plot() axs[index].set_title(cause) plt.sh

我试图创建一个包含9个子图(3 x 3)的图形。十、 Y轴数据来自使用groupby的数据帧。这是我的密码:

fig, axs = plt.subplots(3,3)
for index,cause in enumerate(cause_list):


    df[df['CAT']==cause].groupby('RYQ')['NO_CONSUMERS'].mean().axs[index].plot()
    axs[index].set_title(cause)



plt.show() 
但是,它不会产生所需的输出。事实上,它返回了错误。如果我删除
axs[index]
之前的
plot()
并将
plot()
函数放入
plot(ax=axs[index])
中,则它工作并生成九个子批,但不显示其中的数据(如图所示)。


谁能告诉我哪里出错了吗?

您需要展平axs,否则它是一个2d阵列。您可以提供ax in plot功能,请参见,因此使用一个示例:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

cause_list = np.arange(9)

df = pd.DataFrame({'CAT':np.random.choice(cause_list,100),
                  'RYQ':np.random.choice(['A','B','C'],100),
                  'NO_CONSUMERS':np.random.normal(0,1,100)})

fig, axs = plt.subplots(3,3,figsize=(8,6))
axs = axs.flatten()
for index,cause in enumerate(cause_list):

    df[df['CAT']==cause].groupby('RYQ')['NO_CONSUMERS'].mean().plot(ax=axs[index])
    axs[index].set_title(cause)

plt.tight_layout()

您的原因列表是什么?原因列表过滤数据框。数据框中有九种类型的数据。我想在循环中显示每个子批次
print(df[df['CAT']==cause].groupby('RYQ')['NO_CONSUMERS'].mean())
中的每种类型的数据,并检查output@Pygirl正如我所说,数据帧很长,我正在从输出中粘贴一种类型的数据:RYQ 2016Q1 214.919355 2016Q2 199.676471 2016Q3 230.043956 2016Q4 126.526316 2017Q1 108.934426 2017Q2 136.833333 2017Q3 172.555556 2017Q4 128.937500 2018Q1 198.485714 2018Q2 207.425000 2018Q3 297.958333 2018Q4 113.630769 2019Q1 243.130435 2019Q2 190.4000002019Q3 197.769231 2019Q4 140.152542 2020Q1 221.043478 2020Q2 75.458333 2020Q3 199.451613 2020Q4 203.937500频率:Q-MAR,名称:无消费者,数据类型:float64