matplotlib 在单个 pdf 页面中显示许多图像
matplotlib show many images in single pdf page
给定一个未知大小的图像作为输入,以下 python
脚本在单个 pdf
页面中显示它 8 次:
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()
输入图像可以有不同的大小(先验未知)。我尝试使用函数 gs.update(wspace=xxx, hspace=xxx)
来更改图像之间的间距,希望 matplotlib
会自动调整大小并重新分布图像以尽可能减少白色 space。但是,正如您在下面看到的那样,它并没有像我预期的那样工作。
Is there a better way to go to achieve the following?
- 以可能的最大分辨率保存图像
- 可能space少白
理想情况下,我希望这 8 张图像完全符合 pdf
的页面大小(需要最少的边距)。
您走在正确的道路上:hspace
和 wspace
控制图像之间的 space。您还可以使用 top
、bottom
、left
和 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()
结果:
如果你想让你的图片真正覆盖所有可用的space,那么你可以将宽高比设置为自动:
ax.set_aspect('auto')
结果:
给定一个未知大小的图像作为输入,以下 python
脚本在单个 pdf
页面中显示它 8 次:
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()
输入图像可以有不同的大小(先验未知)。我尝试使用函数 gs.update(wspace=xxx, hspace=xxx)
来更改图像之间的间距,希望 matplotlib
会自动调整大小并重新分布图像以尽可能减少白色 space。但是,正如您在下面看到的那样,它并没有像我预期的那样工作。
Is there a better way to go to achieve the following?
- 以可能的最大分辨率保存图像
- 可能space少白
理想情况下,我希望这 8 张图像完全符合 pdf
的页面大小(需要最少的边距)。
您走在正确的道路上:hspace
和 wspace
控制图像之间的 space。您还可以使用 top
、bottom
、left
和 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()
结果:
如果你想让你的图片真正覆盖所有可用的space,那么你可以将宽高比设置为自动:
ax.set_aspect('auto')
结果: