与图中的多个沼泽地有关 Pandas

Related to multiple swamplots inside a figure Pandas

此问题与 、"individual 28 plots" 有关。 这是我的代码:

for column in df.columns[1:]:
    sns.set()
    fig, ax = plt.subplots(nrows=3, ncols=3) # tried 9 plots in one figure
    sns.set(style="whitegrid")
    sns.swarmplot(x='GF', y=column, data=df,order=["WT", 'Eulomin'])  # Choose column
    sns.despine(offset=10, trim=True) #?
    plt.savefig('{}.png'.format(column), bbox_inches='tight')  #  filename 
plt.show()

我有 100 多列,它会单独保存每个文件,只打印正常文件旁边的空图。我如何在一个图中保存 9 个地块,直到他剩下 5 个(也必须在一个图中)?

不是遍历列,而是使用 range 遍历 9 的倍数以按列号索引数据帧,同时将每个 swarmplot 放入您定义的 ax 数组中:

from itertools import product
...
sns.set(style="whitegrid")

for i in range(1, 100, 9):                         # ITERATE WITH STEPS
    col = i
    fig, ax = plt.subplots(nrows=3, ncols=3, figsize = (12,6)) 

    # TRAVERSE 3 X 3 MATRIX
    for r, c in product(range(3), range(3)):
        if col in range(len(df.columns)):         # CHECK IF COLUMN EXISTS
            # USE ax ARGUMENT WITH MATRIX INDEX
            sns.swarmplot(x='GF', y=df[df.columns[col]], data=df, ax=ax[r,c],
                          order=["WT", 'Eulomin'])
            sns.despine(offset=10, trim=True)
            col += 1

    plt.tight_layout()
    plt.savefig('SwarmPlots_{0}-{1}.png'.format(i,i+8), bbox_inches='tight')

使用 100 列 x 500 行的随机种子数据进行演示以实现再现性:

数据

import numpy as np
import pandas as pd

np.random.seed(362020)
cols = ['Col'+str(i) for i in range(1,100)]
df = (pd.DataFrame([np.random.randn(99) for n in range(500)])
        .assign(GF = np.random.choice(['r', 'python', 'julia'], 500))
        .set_axis(cols + ['GF'], axis='columns', inplace = False)
        .reindex(['GF'] + cols, axis='columns')
     )          

df.shape
# (500, 100)

情节

import matplotlib.pyplot as plt
import seaborn as sns
from itertools import product

sns.set(style="whitegrid")

for i in range(1, 100, 9):
    col = i
    fig, ax = plt.subplots(nrows=3, ncols=3, figsize = (12,6)) 

    for r, c in product(range(3), range(3)):
        if col in range(len(df.columns)):
            sns.swarmplot(x='GF', y=df[df.columns[col]], data=df, ax=ax[r,c])
            col += 1

    plt.tight_layout()
    plt.savefig('SwarmPlots_{0}-{1}.png'.format(i,i+8), bbox_inches='tight')

plt.show()
plt.clf()
plt.close()

输出(第一个情节)