使用不同的函数将多个子图保存为一个pdf

时间:2017-12-28 18:26:29

标签: python python-3.x matplotlib plot

我让用户在“loadingfiles”中使用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'。如果我要在我的main函数中创建一个数字,我怎么能将'fig'传递给函数?

1 个答案:

答案 0 :(得分:0)

您可以从函数返回图形并将其附加到列表中。然后,您可以遍历列表并将数字保存为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函数的循环内创建图形,并将其作为参数传递给绘图函数。

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, fig ,*args):

    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()


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

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

    plt.show()

if __name__=="__main__":
    main()