使用不同的功能将多个子批次保存到一个pdf中

2024-09-19 23:38:07 发布

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

我有一个用户在“加载文件”中使用tkinter选择4个目录。从那里,它从每个目录加载所有文件。 我怎样才能保存所有的子批次到一个PDF格式。我知道我必须从主函数开始,但是我该怎么做呢?在

def loadingfiles():
    #loads all of the files from each directory
    #returns Files

def initialize_and_Calculate(Files=[],*args):

    fig = plt.figure()
    fig.set_size_inches(9,5,forward=True)
    gs1=gridspec.GridSpec(1,2)
    ax0=fig.add_subplot(gs1[0,0])
    ax1=fig.add_subplot(gs1[0,1])


    #treat x and y as a parameter within a file in a directory. Can be any numbers


    ax0.plot(x,y,'-')
    ax1.plot(x1,y1,'-')

    fig.tight_layout()



def main():
    Files=loadingfiles() #this loads the files in directory
    L=len(Files)

    for c in range (0,L): #this for loops runs the initialize_and_Calc. function per directory.
        initialize_and_Calculate(Files[c]) #'File[0]' is directory 1. 'File[1]' is directory 2...and so on

    plt.show()

if __name__=="__main__":
    main()

如果这没有任何意义,那么我如何在函数中传递一个'fig'。假设我要在我的主函数中创建一个图形,如何将fig传递给函数?在


Tags: and文件the函数in目录maindef
1条回答
网友
1楼 · 发布于 2024-09-19 23:38:07

您可以从函数中返回图形并将其附加到列表中。然后您可以循环查看列表并将图保存到pdf文件中。在

from matplotlib import gridspec
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import numpy as np

def loadingfiles():
    return range(4)

def initialize_and_Calculate(Files=[],*args):

    fig = plt.figure()
    fig.set_size_inches(9,5,forward=True)
    gs1=gridspec.GridSpec(1,2)
    ax0=fig.add_subplot(gs1[0,0])
    ax1=fig.add_subplot(gs1[0,1])

    x,y = zip(*np.cumsum(np.random.rand(20,2), axis=0))

    ax0.plot(x,y,'-')
    #ax1.plot(x1,y1,'-')

    fig.tight_layout()
    return fig



def main():
    Files=loadingfiles() 
    figures = []
    for c in range (0,len(Files)):
        figures.append(initialize_and_Calculate(Files[c]))

    with PdfPages('multipage_pdf.pdf') as pdf:
        for f in figures:
            pdf.savefig(f)

    plt.show()

if __name__=="__main__":
    main()

当然,也可以在main函数的循环中创建图形,并将其作为参数传递给plotting函数。在

^{pr2}$

相关问题 更多 >