我正在努力处理matplotlib中的图边距。我使用下面的代码来生成我的图表:

plt.imshow(g)
c = plt.colorbar()
c.set_label("Number of Slabs")
plt.savefig("OutputToUse.png")

然而,我得到的输出数字在图的两边都有大量的空白。我已经搜索了谷歌并阅读了matplotlib文档,但我似乎找不到如何减少这一点。


当前回答

一种自动做到这一点的方法是将bbox_inch ='tight' kwarg转换为plt.savefig。

E.g.

import matplotlib.pyplot as plt
import numpy as np
data = np.arange(3000).reshape((100,30))
plt.imshow(data)
plt.savefig('test.png', bbox_inches='tight')

另一种方法是使用fig.tight_layout()

import matplotlib.pyplot as plt
import numpy as np

xs = np.linspace(0, 1, 20); ys = np.sin(xs)

fig = plt.figure()
axes = fig.add_subplot(1,1,1)
axes.plot(xs, ys)

# This should be called after all axes have been added
fig.tight_layout()
fig.savefig('test.png')

其他回答

最近的matplotlib版本,你可能想尝试约束布局:

Constrained_layout自动调整子图和装饰 图例和颜色条,以便它们适合在图形窗口 仍然尽可能地保留所请求的逻辑布局 用户。 Constrained_layout类似于tight_layout,但是使用了一个约束 求解器来确定轴的大小,使它们适合。 Constrained_layout需要在添加任何轴之前被激活 一个图。

可惜熊猫处理不好…

一种自动做到这一点的方法是将bbox_inch ='tight' kwarg转换为plt.savefig。

E.g.

import matplotlib.pyplot as plt
import numpy as np
data = np.arange(3000).reshape((100,30))
plt.imshow(data)
plt.savefig('test.png', bbox_inches='tight')

另一种方法是使用fig.tight_layout()

import matplotlib.pyplot as plt
import numpy as np

xs = np.linspace(0, 1, 20); ys = np.sin(xs)

fig = plt.figure()
axes = fig.add_subplot(1,1,1)
axes.plot(xs, ys)

# This should be called after all axes have been added
fig.tight_layout()
fig.savefig('test.png')

你可以使用subplots_adjust()函数来调整matplotlib图的间距:

import matplotlib.pyplot as plt
plt.plot(whatever)
plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1)

这既适用于屏幕上的图形,也适用于保存到文件中的图形,即使在一个图形上没有多个图形,也可以调用这个函数。

这些数字是图形尺寸的分数,并且需要调整以允许图形标签。

如果有人想知道如何在应用plt.tight_layout()或fig.tight_layout()后消除其余的白色边距:使用参数pad(默认为1.08),你可以使它更紧凑: “图形边缘和子图边缘之间的填充,作为字体大小的一部分。” 例如,

plt.tight_layout(pad=0.05)

会把利润降低到很小的程度。放0对我没用,因为它使子图的方框也被切断了一点。

plt.savefig("circle.png", bbox_inches='tight',pad_inches=-1)