我试图将一些数据绘制成给定大小的图像(用作覆盖)。然而,尽管调用了set_axis_off()并在savefig上设置了bbox_inches="tight"和pad_inches=0 (就像其他问题中所建议的那样),我仍然得到了填充,并且比图大小更大的图像大小应该会导致填充。
下面是代码( 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),它看起来比预期的要大得多。

发布于 2018-01-08 12:02:51
从bbox_inches="tight"调用中删除savefig。然后,您也不需要pad_inches。
plt.savefig(filename, dpi='figure', transparent=True)这将导致100×100像素的图像。
如果您也不想在轴内有任何边距,将其设置为0,
ax.margins(0)https://stackoverflow.com/questions/48117247
复制相似问题