python - matplotlib show many images in single pdf page -
given image of unknown size input, following python
script shows 8 times in 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 ) # on forth... ax8 = plt.subplot(gs[7]) ax8.imshow( _img ) pdf.savefig() pdf.close()
the input image can have different size (unknown priori). tried using function gs.update(wspace=xxx, hspace=xxx)
change spacing between images, hoping matplotlib
automagically resize , redistribute images have least white space possible. however, can see below, didn't work expected.
is there better way go achieve following?
- have images saved max resolution possible
- have less white space possible
ideally 8 images page size of pdf
(with minimum amount of margin needed).
you on right path: hspace
, wspace
control spaces between images. can control margins on figure top
, bottom
, left
, right
:
import matplotlib.pyplot plt import matplotlib.gridspec gridspec import matplotlib.image mimage 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.) 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 want images cover available space, can set aspect ratio auto:
ax.set_aspect('auto')
result:
Comments
Post a Comment