从matplotlib打印中删除填充

2024-09-27 04:28:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在matplotlib中绘制一个图像,它一直给我一些填充。这就是我尝试过的:

def field_plot():
    x = [i[0] for i in path]
    y = [i[1] for i in path]
    plt.clf()
    plt.axis([0, 560, 0, 820])
    im = plt.imread('field.jpg')
    field = plt.imshow(im)
    for i in range(len(r)):
        plt.plot(r[i][0],r[i][1],c=(rgb_number(speeds[i]),0,1-rgb_number(speeds[i])),linewidth=1)
    plt.axis('off')
    plt.savefig( IMG_DIR + 'match.png',bbox_inches='tight', transparent="True")
    plt.clf()

This is how i see the image


Tags: pathin图像numberfieldforplotmatplotlib
3条回答

尝试使用pad_inches=0,即

plt.savefig( IMG_DIR + 'match.png',bbox_inches='tight', transparent="True", pad_inches=0)

documentation

pad_inches: Amount of padding around the figure when bbox_inches is ‘tight’.

我认为默认值是pad_inches=0.1

这对我有效。绘制后,使用ax=plt.gca()从plt获取Axes对象。然后设置ax对象的xlim和ylim以匹配图像宽度和图像高度。绘图时,Matplotlib似乎会自动增加查看区域的xlim和ylim。请注意,设置y_lim时,必须反转坐标顺序。

for i in range(len(r)):
  plt.plot(r[i][0],r[i][1],c=(rgb_number(speeds[i]),0,1-rgb_number(speeds[i])),linewidth=1)

plt.axis('off')
ax = plt.gca();
ax.set_xlim(0.0, width_of_im);
ax.set_ylim(height_of_im, 0.0);
plt.savefig( IMG_DIR + 'match.png',bbox_inches='tight', transparent="True")

以前的方法对我来说都不太管用,都在图上留下了一些空白。

以下行成功地删除了剩余的白色或透明填充:

plt.axis('off')
ax = plt.gca()
ax.xaxis.set_major_locator(matplotlib.ticker.NullLocator())
ax.yaxis.set_major_locator(matplotlib.ticker.NullLocator())
plt.savefig(IMG_DIR + 'match.png', pad_inches=0, bbox_inches='tight', transparent=True)

相关问题 更多 >

    热门问题