[英]Iterate through columns to generate separate plots in python
我希望我的代碼遍歷列,為每一列繪制一個圖。 我有以下代碼為一列繪制圖,但我不知道如何使用此代碼循環遍歷其他列並為所有列生成圖。 任何的想法?
這是我的代碼:
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
只需將您的代碼放在一個循環中並每次更改列名稱和繪圖名稱就可以了(通過快速測試它對我有效並且我的工作目錄中保存了 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
僅繪制特定的列列表制作要繪制的列列表,然后遍歷該列表在這里,我正在循環繪制回歸圖,長度與高度和寬度與高度。
import matplotlib.pyplot as plt
import seaborn as sns
lst = [ "Length" , "Width" ]
for i in lst:
sns.lmplot(x = 'Height', y = i , data = df ) # df is your dataframe
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.