减少matplotlib图中的左右边距
我在使用matplotlib画图的时候,遇到了处理图表边距的问题。为了生成我的图表,我用了下面的代码:
plt.imshow(g)
c = plt.colorbar()
c.set_label("Number of Slabs")
plt.savefig("OutputToUse.png")
但是,生成的图像两边有很多空白区域。我在谷歌上搜索过,也看过matplotlib的文档,但就是找不到怎么减少这些空白的方法。
13 个回答
75
你只需要在你的输出前加上这个:
plt.tight_layout()
除了减少边距,这样做还可以把任何子图之间的空隙紧凑地排列在一起:
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()
217
你可以通过使用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)
这个方法适用于在屏幕上显示的图形和保存到文件的图形,即使你只有一个图,也可以使用这个函数。
这些数字是图形尺寸的分数,你需要根据图形的标签来调整这些数字,以确保它们不会被遮挡。
376
一种自动处理这个问题的方法是使用 bbox_inches='tight'
这个参数,配合 plt.savefig
函数。
比如:
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')