迭代列以在python中生成单独的图

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

我希望我的代码遍历列,为每列创建一个绘图。我有以下代码为一列绘制绘图,但我不知道如何使用此代码循环遍历其他列并生成所有列的绘图。任何的想法?

这是我的代码:

import seaborn as sns

sns.set()
fig, ax = plt.subplots()
sns.set(style="ticks")
sns.boxplot(x='Location', y='Height [cm]', data=df) 
sns.despine(offset=10, trim=True) 
fig.set_size_inches(22,14)
plt.savefig('Height.pdf', bbox_inches='tight') 

这就是我的数据:

Location            Height          Length       Width    
A                    150             95           18
A                    148             122          25
A                    162             127          16
B                    155             146          32
B                    148             112          21
B                    154             108          30
C                    160             127          22
C                    148             138          36
C                    159             142          28
python
1个回答
1
投票

简单地将代码放在一个循环中并每次更改列名和绘图名称都应该这样做(从快速测试它对我起作用并且我在工作目录中保存了3个PDF):

import matplotlib.pyplot as plt
import seaborn as sns

for column in df.columns[1:]:  # Loop over all columns except 'Location'
    sns.set()
    fig, ax = plt.subplots()
    sns.set(style="ticks")
    sns.boxplot(x='Location', y=column, data=df)  # column is chosen here
    sns.despine(offset=10, trim=True) 
    fig.set_size_inches(22,14)
    plt.savefig('{}.pdf'.format(column), bbox_inches='tight')  # filename chosen here
© www.soinside.com 2019 - 2024. All rights reserved.