我正在努力处理matplotlib中的图边距。我使用下面的代码来生成我的图表:
plt.imshow(g)
c = plt.colorbar()
c.set_label("Number of Slabs")
plt.savefig("OutputToUse.png")
然而,我得到的输出数字在图的两边都有大量的空白。我已经搜索了谷歌并阅读了matplotlib文档,但我似乎找不到如何减少这一点。
我正在努力处理matplotlib中的图边距。我使用下面的代码来生成我的图表:
plt.imshow(g)
c = plt.colorbar()
c.set_label("Number of Slabs")
plt.savefig("OutputToUse.png")
然而,我得到的输出数字在图的两边都有大量的空白。我已经搜索了谷歌并阅读了matplotlib文档,但我似乎找不到如何减少这一点。
当前回答
你所需要的就是
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()
其他回答
受到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])
有时候,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()
如果有人想知道如何在应用plt.tight_layout()或fig.tight_layout()后消除其余的白色边距:使用参数pad(默认为1.08),你可以使它更紧凑: “图形边缘和子图边缘之间的填充,作为字体大小的一部分。” 例如,
plt.tight_layout(pad=0.05)
会把利润降低到很小的程度。放0对我没用,因为它使子图的方框也被切断了一点。