Pagebreak inside Subplot? Matplotlib subplot over mulitple pages

后端 未结 2 1524
清歌不尽
清歌不尽 2021-01-23 03:03

I want to create a python programm that is able to plot multiple graphs into one PDF file, however the number of subplots is variable. I did this already with one plot per page.

2条回答
  •  再見小時候
    2021-01-23 03:42

    A. Loop over pages

    You could find out how many pages you need (npages) and create a new figure per page.

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_pdf import PdfPages
    
    
    tags = ["".join(np.random.choice(list("ABCDEFG123"), size=5)) for _ in range(53)]
    
    N = len(tags)  # number of subplots
    nrows = 5      # number of rows per page
    ncols = 4      # number of columns per page
    
    # calculate number of pages needed
    npages = N // (nrows*ncols)
    if N % (nrows*ncols) > 0:
        npages += 1
    
    pdf = PdfPages('out2.pdf')
    
    for page in range(npages):
        fig = plt.figure(figsize=(8,11))
        for i in range(min(nrows*ncols, N-page*(nrows*ncols))):
            # Your plot here
            count = page*ncols*nrows+i
            ax = fig.add_subplot(nrows, ncols, i+1)
            ax.set_title(f"{count} - {tags[count]}")
            ax.plot(np.cumsum(np.random.randn(33)))
            # end of plotting
    
        fig.tight_layout()
        pdf.savefig(fig)
    
    pdf.close()
    plt.show()
    

    B. Loop over data

    Or alternatively you could loop over the tags themselves and create a new figure once it's needed:

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_pdf import PdfPages
    
    
    tags = ["".join(np.random.choice(list("ABCDEFG123"), size=5)) for _ in range(53)]
    
    nrows = 5      # number of rows per page
    ncols = 4      # number of columns per page
    
    pdf = PdfPages('out2.pdf')
    
    for i, tag in enumerate(tags):
        j = i % (nrows*ncols)
        if j == 0:
            fig = plt.figure(figsize=(8,11))
    
        ax = fig.add_subplot(nrows, ncols,j+1)
        ax.set_title(f"{i} - {tags[i]}")
        ax.plot(np.cumsum(np.random.randn(33)))
        # end of plotting
        if j == (nrows*ncols)-1 or i == len(tags)-1:
           fig.tight_layout()
           pdf.savefig(fig)
    
    pdf.close()
    plt.show()
    

提交回复
热议问题