+-
matplotlib python:fig.figimage和fig.savefig的图形大小
我正在尝试将png图像添加到在 python中使用matplotlib创建的绘图中.

这是我的情节代码

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

该图另存为pdf的513×306 px,但fig.bbox.xmax的值为1650.0 …这就是为什么我的图没有出现的原因….在打印之前如何知道图像的大小,所以我可以知道我的位置在哪里吗?

谢谢

最佳答案
这里发生了两件事:

>如@tcaswell所述,bbox_inches =’tight’裁剪结果图像
>您实际上不是以300 dpi的速度保存图像,而是以100 dpi的速度保存图像

第二项是常见的陷阱.默认情况下,matplotlib将图形保存为与图形的原始dpi不同的dpi(可在rc参数中配置).

为了解决这个问题,请将fig.dpi传递给fig.savefig:

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

为了避免裁切,a)完全不使用bbox_inches =’tight’,或者b)在图内调整大小.完成(b)的一种快速方法是使用fig.tight_layout,尽管不会像使用bbox_inches与savefig那样“紧缩”裁剪.

点击查看更多相关文章

转载注明原文:matplotlib python:fig.figimage和fig.savefig的图形大小 - 乐贴网