Given an image of unknown size as input, the following python
script shows it 8 times in a single pdf
page:
pdf = PdfPages( './test.pdf' )
gs = gridspec.GridSpec(2, 4)
ax1 = plt.subplot(gs[0])
ax1.imshow( _img )
ax2 = plt.subplot(gs[1])
ax2.imshow( _img )
ax3 = plt.subplot(gs[2])
ax3.imshow( _img )
# so on so forth...
ax8 = plt.subplot(gs[7])
ax8.imshow( _img )
pdf.savefig()
pdf.close()
The input image can have different size (unknown a priori). I tried using the function gs.update(wspace=xxx, hspace=xxx)
to change the spacing between the images, hoping that matplotlib
would automagically resize and redistribute the images to have least white space possible. However, as you can see below, it didn't work as I expected.
Is there a better way to go to achieve the following?
Ideally I would like the 8 images to completely will the page size of the pdf
(with minimum amount of margin needed).
The easiest way to display multiple images in one figure is use figure (), add_subplot (), and imshow () methods of Matplotlib. The approach which is used to follow is first initiating fig object by calling fig=plt.figure () and then add an axes object to the fig by calling add_subplot () method.
The issue is that when a user plots a graph in matplotlib and tries to save it as a PDF file in their local system they get an empty file. In the above example, we firstly import matplotlib.pyplot library.
The PDF backend makes one page per figure. Use subplots to get multiple plots into one figure and they'll all show up together on one page of the PDF. Show activity on this post.
If you want to use a multipage pdf file using LaTeX, you need to use from matplotlib.backends.backend_pgf import PdfPages . This version however does not support attach_note. Keywords: matplotlib code example, codex, python plot, pyplot Gallery generated by Sphinx-Gallery
You were on the right path: hspace
and wspace
control the spaces between the images. You can also control the margins on the figure with top
, bottom
, left
and right
:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.image as mimage
from matplotlib.backends.backend_pdf import PdfPages
_img = mimage.imread('test.jpg')
pdf = PdfPages( 'test.pdf' )
gs = gridspec.GridSpec(2, 4, top=1., bottom=0., right=1., left=0., hspace=0.,
wspace=0.)
for g in gs:
ax = plt.subplot(g)
ax.imshow(_img)
ax.set_xticks([])
ax.set_yticks([])
# ax.set_aspect('auto')
pdf.savefig()
pdf.close()
Result:
If you want your images to really cover all the available space, then you can set the aspect ratio to auto:
ax.set_aspect('auto')
Result:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With