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

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

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


当前回答

matplotlibs subplots_adjust的问题是,您输入的值相对于图形的x和y图形大小。这个例子是正确的数字大小打印pdf:

为此,我重新计算了绝对值的相对间距,如下所示:

pyplot.subplots_adjust(left = (5/25.4)/figure.xsize, bottom = (4/25.4)/figure.ysize, right = 1 - (1/25.4)/figure.xsize, top = 1 - (3/25.4)/figure.ysize)

对于一个“figure”的数字。“x维英寸”和“数字”。y尺寸为英寸。因此,整个图形在标签放置范围内左侧空白5mm,底部空白4mm,右侧空白1mm,顶部空白3mm。(x/25.4)的转换已经完成,因为我需要将mm转换为英寸。

注意,x的纯图表大小将是“figure”。Xsize -左边距-右边距”而纯图y的大小将为“图”。Ysize -下距-上距",单位为英寸

其他sniplets(不确定这些,我只是想提供其他参数)

pyplot.figure(figsize = figureSize, dpi = None)

and

pyplot.savefig("outputname.eps", dpi = 100)

其他回答

一种自动做到这一点的方法是将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')

有时候,plt.tight_layout()不会给我最好的视图或我想要的视图。那为什么不先画任意边距然后再确定边距呢? 因为我们从那里得到了很好的所见即所得。

import matplotlib.pyplot as plt

fig,ax = plt.subplots(figsize=(8,8))

plt.plot([2,5,7,8,5,3,5,7,])
plt.show()

然后将设置粘贴到margin函数,使其永久:

fig,ax = plt.subplots(figsize=(8,8))

plt.plot([2,5,7,8,5,3,5,7,])
fig.subplots_adjust(
    top=0.981,
    bottom=0.049,
    left=0.042,
    right=0.981,
    hspace=0.2,
    wspace=0.2
)
plt.show()
# import pyplot
import matplotlib.pyplot as plt

# your code to plot the figure

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

你可以使用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)

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

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

对我来说,上面的答案在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