3

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

Moo10000
  • 115
  • 11
  • Please make a minimal reproducible example that triggers the error. This will help you narrow the problem down. – Jody Klymak Dec 04 '19 at 19:27
  • Done @JodyKlymak, The only thing i noticed in this example, the error is thrown before the if statement, whereas in my actual code it is thrown after the if statement – Moo10000 Dec 04 '19 at 19:46
  • Check [the documentation](https://matplotlib.org/api/backend_pdf_api.html#matplotlib.backends.backend_pdf.PdfPages). You will either need to save before showing the figure, or specify which figure you want to save. – ImportanceOfBeingErnest Dec 04 '19 at 23:41
  • @ImportanceOfBeingErnest In my code, I am not using `plt.show()` and I specify the figure to save but it's not working. What I tried was running the code for the figure in another notebook. I found that although the plots show, they save as blank pdf documents (no pages error when opened) – Moo10000 Dec 05 '19 at 15:48
  • You *do* use `plt.show()` in your code. And you *do not* specify the figure. – ImportanceOfBeingErnest Dec 05 '19 at 15:50
  • Sorry, I should have been more specific, here I do. Not in the actual one code I am using to make the report. The one for the post is a minimal reproducible example @ImportanceOfBeingErnest – Moo10000 Dec 05 '19 at 16:03
  • Well, it seems not well suited as reproducible example if it does something different. Anyways, specifying the figure in the savefig command will solve this. – ImportanceOfBeingErnest Dec 05 '19 at 16:06
  • @ImportanceOfBeingErnest I understand what you mean, I apologize for not updating the code as I made my changes. But I did try what you said, I changed the name of the second figure, and I also tried using plt.gcf() as an argument for savefig as well as savefig(fig2) I threw in the plt.show() again to see if the graph is being made. I attached a picture, the graph is being made just; but is only saved now in the final iteration of the loop (the 63rd pdf only, but not the few earlier ones) – Moo10000 Dec 05 '19 at 16:38
  • Please understand the concept of a [mcve]. There are no 63 figures in your code. – ImportanceOfBeingErnest Dec 05 '19 at 16:42
  • I've made a new example. Does not have 63 but I think it's much closer to that my code is doing. @ImportanceOfBeingErnest – Moo10000 Dec 05 '19 at 17:29
  • 1
    You're overwriting existing files, try `r'Example{}{}.pdf'.format(k, k2)` as filename. – ImportanceOfBeingErnest Dec 05 '19 at 17:43
  • @ImportanceOfBeingErnest I ended up creating a new `with pdfpages` statement in the for loop, and save that pdf to another folder. I will just use a script I have to concatenate the pdf's. I do find this strange though, I use the pdf backend rather often now, and this is the first time I ran into this situation. Usually, when I want new pages, I create a new `fig = plt.figure` I leave the `pdf.savefig()` blank and this seems to just add a new page at the end. – Moo10000 Dec 09 '19 at 03:38

0 Answers0