2

I like to use matplotlib to create a PDF and then I will often go in and tweak things with Adobe Illustrator or Inkscape. Unfortunately, when matplotlib saves the figure as a PDF, it combines multiple images into a single object.

For example, the following code

import matplotlib.pyplot as plt
import numpy as np

im = np.random.rand(10, 10) * 255.0
fig = plt.figure()
ax = fig.add_axes([0.1,0.1,0.8,0.8])
ax.imshow(im, extent = [0,10,0,10])
ax.imshow(im, extent = [12,22,0,10])
ax.set_xlim(-2,24)
fig.savefig('images_get_combined.pdf')

creates the following PDF (after I manually converted to a PNG, so I could post it here) enter image description here When I open images_get_combined.pdf in Adobe Illustrator, both images are combined into a single image. I cannot move one image relative to the other.

I tried to get around this problem using BboxImage, but as shown in this bug report, BboxImage doesn't play nice with the PDF backend. Perhaps the PDF backend with BboxImage bug will get resolved, but I wondered if there is another way to make the PDF backend save each image separately.

1 Answer 1

1

You can try to save as multiple pages PDF:

import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt

im = np.random.rand(10, 10) * 255.0
with PdfPages('images_get_combined.pdf') as pdf:
    fig = plt.figure()
    ax = fig.add_axes([0.1,0.1,0.8,0.8])
    ax.imshow(im, extent = [0,10,0,10])
    pdf.savefig()
    plt.close()
    fig = plt.figure()
    ax = fig.add_axes([0.1,0.1,0.8,0.8])
    ax.imshow(im, extent = [12,22,0,10])
    pdf.savefig()
    plt.close()

See also Multipage PDF example from the matplotlib doc.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the suggestion, but I would rather avoid multiple page pdfs. I typically lay out my figure how I want it in matplotlib, and then stick it in a report. However, sometimes I come back weeks later and realize I want the images in different positions. I don't want to have to recreate the pdf from scratch just to move something.
The official matpotlib FAQ also suggesting a way to save multiple plots to one PDF file as multipage only. I believe if you even make them subplots, you'll get a single image anyway. matplotlib.org/faq/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.