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

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

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


当前回答

只需使用ax = fig.add_axes([左,下,宽,高]) 如果你想要精确控制图形布局。如。

left = 0.05
bottom = 0.05
width = 0.9
height = 0.9
ax = fig.add_axes([left, bottom, width, height])

其他回答

受到sammy回答的启发:

margins = {  #     vvv margin in inches
    "left"   :     1.5 / figsize[0],
    "bottom" :     0.8 / figsize[1],
    "right"  : 1 - 0.3 / figsize[0],
    "top"    : 1 - 1   / figsize[1]
}
fig.subplots_adjust(**margins)

其中figsize是在fig = pyplot.figure(figsize=…)中使用的元组。

# import pyplot
import matplotlib.pyplot as plt

# your code to plot the figure

# set tight margins
plt.margins(0.015, tight=True)

只需使用ax = fig.add_axes([左,下,宽,高]) 如果你想要精确控制图形布局。如。

left = 0.05
bottom = 0.05
width = 0.9
height = 0.9
ax = fig.add_axes([left, bottom, width, height])

对我来说,上面的答案在matplotlib中不起作用。Win7上的__version__ = 1.4.3。因此,如果我们只对图像本身感兴趣(即,如果我们不需要注释、轴、刻度、标题、ylabel等),那么最好是简单地将numpy数组保存为image而不是savefig。

from pylab import *

ax = subplot(111)
ax.imshow(some_image_numpyarray)
imsave('test.tif', some_image_numpyarray)

# or, if the image came from tiff or png etc
RGBbuffer = ax.get_images()[0].get_array()
imsave('test.tif', RGBbuffer)

此外,使用opencv绘图函数(cv2. exe)。Line, cv2.polylines),我们可以直接在numpy数组上做一些绘图。http://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html

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

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

可惜熊猫处理不好…