Skip to content Skip to sidebar Skip to footer

Plot And Save Multiple Figures Of Group By Function As Pdf

I would like to create one pdf file with 12 plots, in two options: one plot per page, four plots per page. Using plt.savefig('months.pdf') saves only last plot. MWE: import panda

Solution 1:

To save a plot in each page use:

from matplotlib.backends.backend_pdf import PdfPages

# create df2withPdfPages('foo.pdf') as pdf:
    for key, groupin df2:
        fig = group.plot().get_figure()
        pdf.savefig(fig)

In order to put 4 plots in a page you need to first build a fig with 4 plots and then save it:

import matplotlib.pyplot as plt
from itertools import islice, chain

defchunks(n, iterable):
    it = iter(iterable)
    whileTrue:
       chunk = tuple(islice(it, n))
       ifnot chunk:
           returnyield chunk

with PdfPages('foo.pdf') as pdf:
    for chunk in chunks(4, df2):
        fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(12, 4))
        axes = chain.from_iterable(axes)  # flatten 2d list of axesfor (key, group), ax inzip(chunk, axes):
            group.plot(ax=ax)

        pdf.savefig(fig)

Post a Comment for "Plot And Save Multiple Figures Of Group By Function As Pdf"