Making copies of figures and selectively writing them to a multipage PDF

s kemp <6b656d70@...287...> writes:

The output i get from this code is two identical pages of PDF where
the x limits are set to 3,5. I understand this is because I am simply
making two identical references to the figure object in the list and
by modifying fig1 i also affect the fig1 that is 'stored' in the first
position of the array. My question is how do I avoid this?

My recommendation is to construct multiple figure objects. Factor the
shared code into a function so it is easier to modify just what you want
to be different between the figures:


import matplotlib.figure as fig
from matplotlib.backends.backend_pdf import PdfPages, FigureCanvasPdf

def plot_data(xdata, ydata):
    """Returns pair of figure and axis"""
    f = fig.Figure(figsize=(2,2))
    ax = f.add_subplot(111)
    ax.plot(xdata, ydata)
    return f, ax

xdata = [1,2,3,4,5]
ydata = [5,4,3,2,1]

fig1, ax1 = plot_data(xdata, ydata)
fig2, ax2 = plot_data(xdata, ydata)

figures = []



pdf = PdfPages('output.pdf')

for figure in figures:
       canvas = FigureCanvasPdf(figure)
       figure.savefig(pdf, format="pdf")


Jouni K. Sepp�nen