我试图将一些数据绘制为给定大小的图像(用作覆盖图)。但是,尽管调用了set_axis_off()
,并在savefig
上设置了bbox_inches="tight"
和pad_inches=0
(如其他问题中所建议的),我仍然得到了填充,并且应该会得到比figsize更大的图像大小。你知道吗
下面是代码(PIL依赖项是为了方便使用,但是可以通过删除最后一行来删除):
from PIL import Image
import matplotlib.pyplot as plt
def plot_box(data, size, filename="plot.png"):
"""Plot the data in an image whose dimensions are size x size pixels"""
fig = plt.figure(figsize=(size/100,size/100), dpi=100)
ax = fig.add_axes((0,0,1,1))
ax.set_axis_off()
ax.plot(data)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.savefig(filename, bbox_inches="tight", pad_inches=0, dpi='figure', transparent=True)
plt.close()
return Image.open(filename)
但是,无论我指定的大小如何,图像在两个方向上总是宽6或7像素:
>> data = [i**2 for i in range(-100, 101)]
>> plot_box(data, 50)
<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=57x57 at 0xED3CB38>
>> plot_box(data, 100)
<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=106x106 at 0xF208908>
>> plot_box(data, 1)
<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=8x8 at 0x53D2748>
有什么想法吗?你知道吗
更新
这是plot_box(data, 100)
的结果图像。正如您所看到的,它看起来很好,除了由于填充(106x106而不是100x100)而比预期的大。你知道吗
从
savefig
调用中删除bbox_inches="tight"
。然后您也不需要pad_inches
。你知道吗这将产生100x100像素的图像。你知道吗
如果你也不想在轴内留有任何边距,就把它设为0
相关问题 更多 >
编程相关推荐