Python 如何将所有seaborn绘图转换为输出png?

Python 如何将所有seaborn绘图转换为输出png?,python,seaborn,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只包

我想根据同一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个图形都写成一个图形

因此,像您这样使用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')

谢谢这是可行的,但是所有的图都被塞进了一个很小的数字,而且有很多黑色标签把图像弄乱了。有没有办法扩大情节的规模?当然有!在实例化图形时,可以更改图形的大小。例如:
fig=plt.figure(figsize=(10,10),dpi=100)