从 matplotlib 绘图中删除填充

问题描述 投票:0回答:6

我正在 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

python django matplotlib padding
6个回答
27
投票

尝试使用

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


8
投票

只需在

plt.tight_layout()
之前添加
plt.savefig()
!!

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

# ... Doing Something ...

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

5
投票

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

4
投票

使用

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

3
投票

之前的所有方法对我来说都不太有效,它们都在人物周围留下了一些填充。

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

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)

0
投票

所以这是给所有和我有同样问题的人的。当我使用 pad_inches 等删除填充时,尺寸会发生变化。对我有用的解决方案:

plt.tight_layout(pad=0)

就在之后 图,ax = plt.subplots(figsize =(宽度,高度),frameon = False)

并结合以下内容: plt.savefig(f'{image_name}.png', bbox_inches='紧', pad_inches=0)

© www.soinside.com 2019 - 2024. All rights reserved.