Matplotlib savefig into different pages of a PDF

前端 未结 3 829
眼角桃花
眼角桃花 2020-12-16 19:14

I have a lengthy plot, composed o several horizontal subplots organized into a column.

When I call fig.savefig(\'what.pdf\'), the resulting output file shows all the

相关标签:
3条回答
  • 2020-12-16 19:57

    I suspect that there is a more elegant way to do this, but one option is to use tempfiles or StringIO to avoid making traditional files on the system and then you can piece those together.

    0 讨论(0)
  • 2020-12-16 19:58

    I was wondering how to perform a similar thing. I have a set plots coming from different image files, which vary depending on the file. So the idea is, once I found a nice number of plots that can be plotted in a page, apply this for the files. Luckly, I found a solution suggested here: http://blog.marmakoide.org/?p=94. However it does not work correctly, since it only plots the first panel plots, leaving the rest of the panels empty. I modified it and here I include a working version for a (1XN) grid and the output plots.

    import numpy
    
    from matplotlib import pyplot as plot
    from matplotlib.backends.backend_pdf import PdfPages
    
    # Generate the data
    data = numpy.random.randn(7, 1024)
    
    # The PDF document
    pdf_pages = PdfPages('histograms.pdf')
    
    # Generate the pages
    nb_plots = data.shape[0]
    nb_plots_per_page = 5
    nb_pages = int(numpy.ceil(nb_plots / float(nb_plots_per_page)))
    grid_size = (nb_plots_per_page, 1)
    
    for i, samples in enumerate(data):
      print
      print i,i % nb_plots_per_page,samples
      # Create a figure instance (ie. a new page) if needed
      if i % nb_plots_per_page == 0:
        print 'Opening'
        fig = plot.figure(figsize=(8.27, 11.69), dpi=100)
      # Close the page if needed
      elif (i + 1) % nb_plots_per_page == 0 or (i + 1) == nb_plots:
        plot.subplot2grid(grid_size, (i % nb_plots_per_page, 0))
        plot.hist(samples, 32, normed=1, facecolor='#808080', alpha=0.75)
        plot.title(str(i+1))
    
        plot.tight_layout()
        pdf_pages.savefig(fig)
        print 'Closing'
        print i,samples
        # Plot stuffs !
      print i,samples
      plot.subplot2grid(grid_size, (i % nb_plots_per_page, 0))
      plot.hist(samples, 32, normed=1, facecolor='#808080', alpha=0.75)
      plot.title(str(i+1))
    
    
    # Write the PDF document to the disk
    pdf_pages.close()
    print 'histograms.pdf'
    

    0 讨论(0)
  • 2020-12-16 20:09

    I haven't tried myself, but in the matplolib faq there are some instruction to save plots in pdf in several pages.

    • FAQ http://matplotlib.org/faq/howto_faq.html#save-multiple-plots-to-one-pdf-file
    • Example http://matplotlib.org/examples/pylab_examples/multipage_pdf.html
    0 讨论(0)
提交回复
热议问题