-2

I am trying to save several plots in a for loop but I got this error: 'FileNotFoundError: [Errno 2] No such file or directory: '8/2020/graph.png'

Here is my code:

for i in names.columns:

fig, ax = plt.subplots(1,1,figsize=(150,50))    
g1 = sns.heatmap(df, cmap="Spectral", 
                  cbar_kws={'shrink': 0.85}, 
                )

# plt.savefig(i + 'graph.png')
fig.savefig('{}/graph.png'.format(i))

plt.show()

But when I use ---> plt.savefig('seaborn_change_colormap_size_02.png') my code works but the problem that at the end I will have only one plot (the last one).

Any ideas how can I save all plots in different names?

Yaman
  • 1

1 Answers1

1

You'll have to create the directory if it doesn't already exist.

import os

for i in names.columns:

    fig, ax = plt.subplots(1,1,figsize=(150,50))    
    g1 = sns.heatmap(df, cmap="Spectral", 
                  cbar_kws={'shrink': 0.85}, 
                )

    if not os.path.isdir(i):
        os.mkdir(i)
    fig.savefig(f'{i}/graph.png')
Bendik Knapstad
  • 1,409
  • 1
  • 9
  • 18