2013-05-02 770 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的方式“严格”裁剪。