Matplotlib 正在使用for循环验证plt.subplot()返回的Axis对象

Matplotlib 正在使用for循环验证plt.subplot()返回的Axis对象,matplotlib,seaborn,Matplotlib,Seaborn,我试图使用for循环,通过以下代码填充子批次中的每个轴: df = sns.load_dataset('iris') cols = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width'] # plotting fig, ax = plt.subplots(2,2) for ax_row in range(2): for ax_col in range(2): for col in cols:

我试图使用for循环,通过以下代码填充
子批次中的每个

df = sns.load_dataset('iris')
cols = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width']
# plotting
fig, ax = plt.subplots(2,2)
for ax_row in range(2):
    for ax_col in range(2):
        for col in cols:
            sns.distplot(df[col], ax=ax[ax_row][ax_col])

但我在四个轴上得到了相同的图。我应该如何更改它以使其工作?

问题是col-in-cols的
在其中循环遍历每个子批次的所有列。相反,您需要在一个子图中一次绘制一列。要做到这一点,一种方法是使用索引
i
,并在循环子批次时不断更新它。以下是答案:

import seaborn as sns
df = sns.load_dataset('iris')
cols = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width']
# plotting
fig, ax = plt.subplots(2,2, figsize=(8, 6))
i = 0
for ax_row in range(2):
    for ax_col in range(2):
        ax_ = sns.distplot(df[cols[i]], ax=ax[ax_row][ax_col])
        i += 1
plt.tight_layout()  
编辑:使用
枚举

fig, ax = plt.subplots(2,2, figsize=(8, 6))
for i, axis in enumerate(ax.flatten()):        
    ax_ = sns.distplot(df[cols[i]], ax=axis)
plt.tight_layout()  
编辑2:在
cols

fig, axes = plt.subplots(2,2, figsize=(8, 6))
for i, col in enumerate(cols):        
    ax_ = sns.distplot(df[col], ax=axes.flatten()[i])
plt.tight_layout()  

我假设
ax[ax\u row][ax\u col]=sns.distplot(df[cols[I]])
也会做同样的事情,但为什么这些图会再次出现在轴上呢。我错过什么了吗?你有多余的吗?你能说得更具体一点吗?我还在挣扎。我想你可以索引每个轴,并将它们分配给sns绘图。。。史蒂文:是的,我在回答中加了一句。如果有帮助,您可以向上投票确定,请选中编辑2