如何将所有Seaborn地块转换为输出png?

时间:2019-05-05 11:30:11

标签: python seaborn

我想针对同一df中的一列绘制数据框中的所有列:totCost。以下代码可以正常工作:

for i in range(0, len(df.columns), 5):
    g=sns.pairplot(data=df,
            x_vars=df.columns[i:i+5],
            y_vars=['totCost'])
    g.set(xticklabels=[])
    g.savefig('output.png')

问题是output.png仅包含最后3个图(总共18个图)。如果我缩进那条线,也会发生同样的情况。如何将所有18个都写为一个图形?

1 个答案:

答案 0 :(得分:1)

因此,像您一样使用pairplot的问题在于,在循环的每次迭代中,都会创建一个新图形并将其分配给g

如果将循环的最后一行代码g.savefig('output.png')带到循环之外,则仅将g的最后一个版本保存到磁盘,这是其中只有最后三个子图的那个版本

如果将那条线放入循环中,所有图形都将保存到磁盘上,但名称相同,最后一个当然是其中包含三个子图的图形。

一种解决方法是创建一个图形,并将所有子图分配给它,然后将其保存到磁盘:

import matplotlib.pyplot as plt

import pandas as pd
import numpy as np
import seaborn as sns

# generate random data, with 18 columns
dic = {str(a): np.random.randint(0,10,10) for a in range(18)}
df = pd.DataFrame(dic)

# rename first column of dataframe
df.rename(columns={'0':'totCost'}, inplace=True)

#instantiate figure
fig = plt.figure()

# loop through all columns, create subplots in 5 by 5 grid along the way,
# and add them to the figure
for i in range(len(df.columns)):
    ax = fig.add_subplot(5,5,i+1)
    ax.scatter(df['totCost'], df[df.columns[i]])
    ax.set_xticklabels([])

plt.tight_layout()

fig.savefig('figurename.png')