Search code examples
pythongraphpngseaborn

Seaborn plt.savefigure 'overwriting images'


Problem

I'm trying to save graphs with seaborn and matplotlib plt.savefig('.png'), but what is happening is that the graphs are being overwritten, even when the name is different. I can't use

fig = sns.lineplot(data=totaldf, palette="tab10", linewidth=2.5) fig.savefig('.png')

because it returns:

AttributeError: 'AxesSubplot' object has no attribute 'savefig'

How can I save this graphs without overwrite?

Code

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

maindf = pd.read_csv('df2.csv')
maindf['M01']=(maindf['M01'].apply(lambda x: x * 27))
maindf['M02']=(maindf['M02'].apply(lambda x: x * 27))
maindf['M03']=(maindf['M03'].apply(lambda x: x * 27))
maindf['M04']=(maindf['M04'].apply(lambda x: x * 27))
maindf['M05']=(maindf['M05'].apply(lambda x: x * 27))
maindf['M06']=(maindf['M06'].apply(lambda x: x * 27))
maindf['M07']=(maindf['M07'].apply(lambda x: x * 27))
maindf['M08']=(maindf['M08'].apply(lambda x: x * 27))
maindf['M09']=(maindf['M09'].apply(lambda x: x * 27))
maindf['M10']=(maindf['M10'].apply(lambda x: x * 27))
maindf['M11']=(maindf['M11'].apply(lambda x: x * 27))
maindf['M12']=(maindf['M12'].apply(lambda x: x * 27))
maindf['M13']=(maindf['M13'].apply(lambda x: x * 27))
maindf['M14']=(maindf['M14'].apply(lambda x: x * 27))
maindf['M15']=(maindf['M15'].apply(lambda x: x * 27))
index=0
totaldf = pd.DataFrame({ 'Pontuacao Total':maindf.sum(axis=1)})
sns.countplot(totaldf['Pontuacao Total'])
plt.savefig("PontuacaoTotalDistPlot.png")
sns.heatmap(totaldf,cmap = 'inferno_r')
plt.savefig('PontuacaoTotalHeatmap.png')
sns.lineplot(data=totaldf, palette="tab10", linewidth=2.5)
plt.savefig('PontuacaoTotalLine.png')

Images

That's the lineplot

That's the line plot

That's the heatmap

That's the heatmap


Solution

  • You can create a new figure for each plot,

    plt.figure()
    sns.countplot(...)
    plt.savefig(...)
    
    plt.figure()
    sns.lineplot(...)
    plt.savefig(...)
    

    You can also save any specific figure,

    fig1 = plt.figure()
    sns.countplot(...)
    
    fig2 = plt.figure()
    sns.lineplot(...)
    
    fig1.savefig(...)
    fig2.savefig(...)