为什么我的matplotlib pdf分页上下文管理器在python 2中不起作用?

时间:2017-05-09 18:53:04

标签: python python-2.7 python-3.x matplotlib

我一直在编写以下上下文管理器+迭代器类,以自动生成每页指定轴数的多页pdf,并根据需要添加新页面。它在python3下工作正常,但是在python2中我最后会在最后一页上显示空白图。有什么想法吗?

from future.utils import implements_iterator
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages, FigureCanvasPdf
from matplotlib.figure import Figure


@implements_iterator
class PdfPaginator(object):
    def __init__(self, pdfpages, nrow, ncol, **kwargs):
        self.pdfpages = pdfpages
        self.nrow = nrow
        self.ncol = ncol
        self.naxes = nrow*ncol
        self.kwargs = kwargs

        self.i = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.i % self.naxes == 0:
            # If current fig exists, clean it up before creating a new fig
            if self.i != 0:
                self.pdfpages.savefig(self.fig)
            self.fig, self.axes = self.subplots(
                    self.nrow, self.ncol, **self.kwargs)
        self.i += 1
        return self.axes.ravel()[(self.i-1) % self.naxes]

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self.pdfpages.savefig(self.fig)

    @staticmethod
    def subplots(nrow, ncol, **kwargs):
        fig = Figure(**kwargs)
        # Following line seems to be required, but I'm not sure why.
        FigureCanvasPdf(fig)
        axes = [[fig.add_subplot(nrow, ncol, i+ncol*j+1)
                 for i in range(ncol)]
                for j in range(nrow)]
        return fig, np.array(axes, dtype=object)

if __name__ == '__main__':
    x = np.random.normal(size=(50, 50))
    y = np.random.normal(size=(50, 50))

    with PdfPages("blah.pdf") as pdf:
        with PdfPaginator(pdf, 3, 4, figsize=(8.5, 11)) as p:
            for x_, y_, ax in zip(x, y, p):
                ax.plot(x_, y_)

0 个答案:

没有答案