如何停止在matplotlib PdfPages函数的PDF输出中创建额外页面

2024-07-04 17:02:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我搞不懂为什么我的PDF文件里多了一页。我只有7个文件是加载,但有8个是创建在PDF输出文件。下面是我正在使用的代码。所加载的文件实际上是一个文件的副本,每个文件都重命名为不同的名称以避免问题我不认为实际内容是相同的这一事实应该很重要,对吧?在

编辑:我已经能够验证这是最后一个加载并添加到PDF文件中的文件创建了两次,但我还是不明白为什么。。在

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)

Tags: 文件forpdfplotnpcounterpltfile

热门问题