Python 减少 matplotlib 图中的左右边距
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4042192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reduce left and right margins in matplotlib plot
提问by robintw
I'm struggling to deal with my plot margins in matplotlib. I've used the code below to produce my chart:
我正在努力处理 matplotlib 中的情节边距。我使用下面的代码来生成我的图表:
plt.imshow(g)
c = plt.colorbar()
c.set_label("Number of Slabs")
plt.savefig("OutputToUse.png")
However, I get an output figure with lots of white space on either side of the plot. I've searched google and read the matplotlib documentation, but I can't seem to find how to reduce this.
但是,我得到的输出图在图的两侧都有很多空白。我搜索过谷歌并阅读了 matplotlib 文档,但我似乎无法找到如何减少这种情况。
采纳答案by Joe Kington
One way to automatically do this is the bbox_inches='tight'kwarg to plt.savefig.
自动执行此操作的一种方法是bbox_inches='tight'kwarg to 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')
Another way is to use fig.tight_layout()
另一种方法是使用 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')
回答by DaveP
You can adjust the spacing around matplotlib figures using the subplots_adjust() function:
您可以使用 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)
This will work for both the figure on screen and saved to a file, and it is the right function to call even if you don't have multiple plots on the one figure.
这适用于屏幕上的图形并保存到文件中,即使在一个图形上没有多个绘图,它也是正确的调用函数。
The numbers are fractions of the figure dimensions, and will need to be adjusted to allow for the figure labels.
这些数字是图形尺寸的分数,需要进行调整以允许图形标签。
回答by Tian Chu
plt.savefig("circle.png", bbox_inches='tight',pad_inches=-1)
回答by Sammy
The problem with matplotlibs subplots_adjust is that the values you enter are relative to the x and y figsize of the figure. This example is for correct figuresizing for printing of a pdf:
matplotlibs subplots_adjust 的问题在于您输入的值与图形的 x 和 y figsize 相关。此示例用于正确打印 pdf 的图形大小:
For that, I recalculate the relative spacing to absolute values like this:
为此,我将相对间距重新计算为绝对值,如下所示:
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)
for a figure of 'figure.xsize' inches in x-dimension and 'figure.ysize' inches in y-dimension. So the whole figure has a left margin of 5 mm, bottom margin of 4 mm, right of 1 mm and top of 3 mm within the labels are placed. The conversion of (x/25.4) is done because I needed to convert mm to inches.
对于 x 维度中的 'figure.xsize' 英寸和 y 维度中的 'figure.ysize' 英寸的数字。所以整个图形的左边距为 5 毫米,底部边距为 4 毫米,右边为 1 毫米,顶部为 3 毫米,放置标签。(x/25.4) 的转换已完成,因为我需要将毫米转换为英寸。
Note that the pure chart size of x will be "figure.xsize - left margin - right margin" and the pure chart size of y will be "figure.ysize - bottom margin - top margin" in inches
请注意,x 的纯图表大小将为“figure.xsize - 左边距 - 右边距”,y 的纯图表大小将为“figure.ysize - 底部边距 - 顶部边距”(以英寸为单位)
Other sniplets (not sure about these ones, I just wanted to provide the other parameters)
其他片段(不确定这些片段,我只是想提供其他参数)
pyplot.figure(figsize = figureSize, dpi = None)
and
和
pyplot.savefig("outputname.eps", dpi = 100)
回答by user2065406
All you need is
所有你需要的是
plt.tight_layout()
before your output.
在你的输出之前。
In addition to cutting down the margins, this also tightly groups the space between any subplots:
除了减少边距之外,这还将任何子图之间的空间紧密地分组:
x = [1,2,3]
y = [1,4,9]
import matplotlib.pyplot as plt
fig = plt.figure()
subplot1 = fig.add_subplot(121)
subplot1.plot(x,y)
subplot2 = fig.add_subplot(122)
subplot2.plot(y,x)
fig.tight_layout()
plt.show()
回答by otterb
For me, the answers above did not work with matplotlib.__version__ = 1.4.3on Win7. So, if we are only interested in the image itself (i.e., if we don't need annotations, axis, ticks, title, ylabel etc), then it's better to simply save the numpy array as image instead of savefig.
对我来说,上面的答案matplotlib.__version__ = 1.4.3在 Win7 上不起作用。因此,如果我们只对图像本身感兴趣(即,如果我们不需要注释、轴、刻度、标题、ylabel 等),那么最好将 numpy 数组保存为图像而不是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)
Also, using opencv drawing functions (cv2.line, cv2.polylines), we can do some drawings directly on the numpy array. http://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html
另外,使用opencv绘图函数(cv2.line,cv2.polylines),我们可以直接在numpy数组上做一些绘图。http://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html
回答by mason
Just use ax = fig.add_axes([left, bottom, width, height])if you want exact control of the figure layout. eg.
只要使用ax = fig.add_axes([left, bottom, width, height]),如果你想图布局的精确控制。例如。
left = 0.05
bottom = 0.05
width = 0.9
height = 0.9
ax = fig.add_axes([left, bottom, width, height])
回答by michaelosthege
inspired by Sammys answer above:
受上述 Sammys 回答的启发:
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)
Where figsize is the tuple that you used in fig = pyplot.figure(figsize=...)
其中 figsize 是您使用的元组 fig = pyplot.figure(figsize=...)
回答by Oberwaschlappen
In case anybody wonders how how to get rid of the rest of the white margin after applying plt.tight_layout()or fig.tight_layout(): With the parameter pad(which is 1.08by default), you're able to make it even tighter:
"Padding between the figure edge and the edges of subplots, as a fraction of the font size."
So for example
如果有人想知道如何在应用plt.tight_layout()或之后去除其余的白边fig.tight_layout():使用参数pad(1.08默认情况下),您可以使其更紧密:“图形边缘和边缘之间的填充子图,作为字体大小的一小部分。” 所以例如
plt.tight_layout(pad=0.05)
will reduce it to a very small margin. Putting 0doesn't work for me, as it makes the box of the subplot be cut off a little, too.
将其减少到很小的幅度。Putting0对我不起作用,因为它也会使子图的框被切掉一点。
回答by Michel de Ruiter
With recent matplotlib versions you might want to try Constrained Layout.
使用最近的 matplotlib 版本,您可能想尝试Constrained Layout。

