2013-05-02 176 views
3

我試圖添加一個PNG圖像到在Python中使用matplotlib創建的圖。matplotlib + python:fig.figimage和fig.savefig的圖尺寸

這裏是我的陰謀代碼

import matplotlib as mpl 
mpl.use('Agg') 
import matplotlib.pyplot as plt 


fig = plt.figure(figsize=(5.5,3),dpi=300) 
ax = fig.add_subplot(111) 
ax.grid(True,which='both') 

ax.plot([0,1,2,3],[5,2,6,3],'o') 

xlabel = ax.set_xlabel('xlab') 
ax.set_ylabel('ylab') 


from PIL import Image 
import numpy as np 

im = Image.open('./lib/Green&Energy-final-roundonly_xsmall.png') 
im_w = im.size[0] 
im_h = im.size[1] 
# We need a float array between 0-1, rather than 
# a uint8 array between 0-255 
im = np.array(im).astype(np.float)/255 

fig.figimage(im,fig.bbox.xmax - im_w - 2,2,zorder=10) 
fig.savefig('test.png',bbox_extra_artists=[xlabel], bbox_inches='tight') 

這個數字已經513x306像素保存爲PDF格式,但fig.bbox.xmax1650.0 ...這就是爲什麼我的身影沒有出現....我怎麼能在打印之前知道圖像的大小,所以我可以知道把我的im放在哪裏?

感謝

+1

取出'bbox_inches ='tight''這是收縮包裝邊框,所以你失去了對最終尺寸的一些控制。 – tacaswell 2013-05-02 14:50:48

+0

[這] [1]答案可能是你要找的。 [1]:http://stackoverflow.com/a/15145013/2297781 – Saethlin 2015-09-15 15:52:25

回答

3

兩件事情都發生在這裏:

  1. 作爲@tcaswell提到,bbox_inches='tight'作物產生的圖像向下
  2. 你沒有真正300 dpi的分辨率保存圖像,你將其保存爲100 dpi

第二項是一個常見的問題。默認情況下,matplotlib以不同的dpi(可在rc params中配置)保存圖形的原始dpi。

爲了解決這個問題,通過在fig.dpifig.savefig

fig.savefig(filename, dpi=fig.dpi, ...) 

要解決裁剪下來的東西,無論是)離開bbox_inches='tight'出完全,或者b)調整的身影裏面的東西來代替。完成(b)的一個快速方法是使用fig.tight_layout,雖然它不會像使用savefig一樣使用bbox_inches的方式「嚴格」裁剪。