pythonnumpymatplotlibscipypdfpages

How to stop extra page being created in PDF output from matplotlib PdfPages function


I can't figure out why I'm getting an extra page in my PDF file. I only have 7 files that are loaded but 8 are being created in the PDF output file. Below is the code I'm working with. The files being loaded are actually copies of one file each renamed to a different name to avoid problems I don't think the fact that the actual content is the same should matter right?

Edit: I have been able to verify that it's the last file that's loaded and added to the PDF file that gets created twice but I still don't see why..

def processFiles():
    ##Set some vars
    global kdeData
    counter = 0
    sColumn = selectCol()
    sSamples = setSamples()
    rfName = raw_input("Name of file to save results to: ")+".pdf"
    createPDF = PdfPages(rfName)

    ##Iterate for each file
    for file in fileList:
        valid = [sColumn]
        matrix = np.loadtxt(file, skiprows=1, usecols=valid)
        colCount = np.loadtxt(file, dtype=object)
        totalCols = colCount.shape[1]

        ldlValid = [i for i in range(totalCols)]
        lDL = np.loadtxt(file, usecols=ldlValid, dtype=object)

        kdeData = np.array(matrix)

        gkde = stats.gaussian_kde(kdeData)
        ind = np.linspace(-int(getRange()), int(getRange()), len(kdeData) * sSamples)
        kdepdf = gkde.evaluate(ind)
        plt.figure()

        ##plot histogram of sample
        plt.hist(kdeData, len(kdeData), normed=1, alpha=0.20)
        ##plot data generating density
        plt.plot(ind, stats.norm.pdf(ind), 'r', linewidth=0.8, label='DGP normal')
        ##plot estimated density
        plt.plot(ind, kdepdf, 'g', linewidth=0.8, label='kde')
        plt.title('KDE for '+str(nameList[counter]))
        plt.legend()
        plt.savefig(createPDF, format='pdf')
        counter += 1

    ##Save PDF and open it
    createPDF.savefig()
    createPDF.close()
    os.startfile(rfName)

Solution

  • It's the extra createPDF.savefig() two lines up from the bottom.