繁体   English   中英

从 matplotlib 绘图中删除填充

[英]Remove padding from matplotlib plotting

我在 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()

这就是我看到的图像

尝试使用pad_inches=0 ,即

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

文档中:

pad_inches:当 bbox_inches 为“紧”时图形周围的填充量。

我认为默认是pad_inches=0.1

只需在plt.tight_layout() plt.savefig() !!

plt.figure(figsize=(16, 10))

# ... Doing Something ...

plt.tight_layout()
plt.savefig('wethers.png')
plt.show()

这对我有用。 绘图后,使用 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)

使用plt.gca().set_position((0, 0, 1, 1))让轴跨越整个图形,请参阅参考资料 如果使用plt.imshow ,则要求图形具有正确的纵横比。

import matplotlib as mpl
import matplotlib.pyplot as plt

# set the correct aspect ratio
dpi = mpl.rcParams["figure.dpi"]
plt.figure(figsize=(560/dpi, 820/dpi))

plt.axis('off')
plt.gca().set_position((0, 0, 1, 1))

im = plt.imread('field.jpg')
plt.imshow(im)

plt.savefig("test.png")
plt.close()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM