2015-04-01 45 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