0

I find the matplotlib example not convenient when you have a long code. Its "with" block must embrace the whole code. Is the any way to avoid it when printing several plots?

with PdfPages('multipage_pdf.pdf') as pdf:
    plt.figure(figsize=(3, 3))
    plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o')
    plt.title('Page One')
    pdf.savefig()  # saves the current figure into a pdf page
    plt.close()
aiv
  • 37
  • 1
  • 5
  • What do you find inconvenient? I get the sense that you want to somehow define a *loop* that generates a different plot on each iteration, rather than repeating variations of the same code to generate the plots (which has little to do with whether or not you use a `with` statement). – chepner Mar 19 '23 at 14:18
  • Imagine you have to compute several complex graphs and print them. Many routines have to be set inside this with block. When I can write into a csv file any time, why can't I do the same with pdf prints? – aiv Mar 19 '23 at 15:10
  • Instead of me having to imagine anything, why don't you provide an example of code you find incovenient? (You would typically be using a `with` statement to open the CSV file you'll be writing to; this isn't terribly different.) – chepner Mar 19 '23 at 15:13
  • E.g. export all plots from this notebook in one pdf: https://github.com/yhilpisch/aiif/blob/main/code/07_dense_networks.ipynb – aiv Mar 19 '23 at 15:29

1 Answers1

0

I've found the answer here. Just create pdf object, call savefig on each plot and close when done.

aiv
  • 37
  • 1
  • 5