pdf savefig gives 'no figure none' value error, but works in lines above

1k Views Asked by At

I was using this code earlier to make some plots, but for some reason, the code is throwing me an error. I thought I had made a typo but that does not seem to be the case.

    #%%

import random
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib import rc
nice = ['#899477', '#4da1a9', '#e59500','#7f99b1', '#7d4559',]
from matplotlib.gridspec import GridSpec
import matplotlib.pyplot as plt
import numpy as np
r1 = random.sample(range(12), 5)
r2 = random.sample(range(13), 5)
r3 = random.sample(range(14), 5)
r4 = random.sample(range(15), 5)

#%%

df1 = pd.DataFrame({'location':[1,2,3,4,5], 'bar1':r2, 'bar2':r3})
df2 = pd.DataFrame({'location':[2,4,1,1,1], 'bar3':r4, 'bar1':r1})

#%%
d1 = dict(tuple(df1.groupby('location')))
d2 = dict(tuple(df2.groupby('location')))
#%%
for k, v in d1.items():
    for k2, v2 in d2.items():
        with PdfPages(r'{} Example.pdf'.format(k)) as pdf:
            fig = plt.figure(figsize = (8,10.5))
            gs=GridSpec(3,2) # 2 rows, 3 columns
            ax1 = fig.add_subplot(gs[0,:])
            plt.sca(ax1)
            plt.bar(x=np.arange(5), height = v['bar2'], color = nice)
            pdf.savefig(fig)
            if k == k2:
                fig2 = plt.figure(figsize = (8,10.5))
                gs=GridSpec(3,2) 
                ax2 = fig.add_subplot(gs[0,:])
                plt.sca(ax2)
                plt.barh(y=np.arange(len(v2.bar3)), width = v2['bar3'], color = nice)
                plt.gcf()
                pdf.savefig(fig2)
                plt.show()

Following the advice from comments, I tried specifying the figure but now the it's only saved in the last pdf made by the first for loop I have. Also, changed that last graph to seaborn plot just to try something different What my Python IDE shows

0

There are 0 best solutions below