2015-04-01 83 views
7

鉴于未知大小作为输入的图像许多图像,下面的python脚本显示它在单个pdf页8次:matplotlib显示在单个PDF页面

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会自动地调整和重新分配的图像具有至少空白可能。但是,正如您在下面看到的那样,它并没有按照我的预期工作。

有没有一种更好的方式去实现以下?

  1. 有图像保存最大分辨率可能
  2. 有更少的空白区域可能

理想我想在8个图像将完全与pdf的页面大小(以最小量需要保证金)。

enter image description here

enter image description here

+0

我的答案能解决您的问题吗? – hitzg 2015-04-20 10:02:53

+0

@hitzg - 是的!我在等待更多的反馈意见,但却完全忘了接受。抱歉! – Matteo 2015-04-20 16:52:29

回答

12

你是在正确的道路上:hspacewspace控制图像之间的空间。您还可以控制利润的数字与topbottomleftright

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() 

结果:

enter image description here

如果你希望你的图像真正覆盖所有的可用空间,然后您可以将纵横比设置为自动:

ax.set_aspect('auto') 

Resulul t:

enter image description here