如何控制matplotlib中图形周围的空白?(plt.tight_layout不起作用)

时间:2016-10-03 21:43:08

标签: python numpy matplotlib plot

我有一个带有3个子图的matplotlib图。 stackexchange的共识似乎是使用plt.tight_layout来摆脱图周围的空白。这并不能解决我的问题。

我的代码如下:

import numpy as np
import os
import pandas as pd
import matplotlib as mpl
from matplotlib import pyplot as plt

my_dpi = 1500
plt.ion()

index = np.linspace(0,5,10)
combined = np.linspace(0,1,10)
case1 = np.linspace(0,1,10)
case2 = np.linspace(0,1,10)
case3 = np.linspace(0,1,10)

tsfont = {'fontname':'Times-Roman'}
mpl.rcParams.update({'font.size': 18})
mpl.rc('font',family='Arial')
ms = 0

f = plt.figure()
f.set_size_inches(7.5,10)
f.axison=False


lw = 2
asp = 5


axarr1 = plt.subplot(3,1,1, adjustable='box',aspect = asp)

axarr1.set_xlim(0,5,10)
axarr1.set_ylim(0,1)
axarr1.set_ylabel('y')
axarr1.set_xlabel('$\\tau$', fontsize =25)
p = axarr1.plot(index,combined,color='navy', linewidth=lw, label = "Healthy")
axarr1.xaxis.set_label_coords(0.5, -0.05)


'''
Duct 2
'''

axarr2 = plt.subplot(3,1,2, adjustable='box',aspect = asp)
#axarr2.set_aspect('auto')
axarr2.set_xlim(0,5,10)
axarr2.set_ylim(0,1)
axarr2.set_ylabel('y')
axarr2.set_xlabel('$\\tau$', fontsize = 25)
g = axarr2.plot(index,combined,color='navy', linewidth=lw)
axarr2.xaxis.set_label_coords(0.5, -0.05)

'''
Duct 3
'''

axarr3 = plt.subplot(3,1,3, adjustable='box',aspect = asp)

axarr3.set_xlim(0,5,10)
axarr3.set_ylim(0,1)
axarr3.set_ylabel('y')
axarr3.set_xlabel('$\\tau$', fontsize = 25)
w = axarr3.plot(index,combined,color='navy', linewidth=lw)
axarr3.xaxis.set_label_coords(0.5, -0.05)

#plt.tight_layout()
plt.show()

不使用plt.tight_layout()我得到以下结果

enter image description here

取消注释相关行给我

As is obvious, while the vertical spacing changes, the horizontal spacing does not

很明显,当垂直间距发生变化时,水平间距不会

我想知道如何摆脱左右两侧的水平whitespacing。

1 个答案:

答案 0 :(得分:0)

tight_layout选项可使图像更靠近边框。但是,在您的情况下,没有任何东西可以填充这个空白区域,因此它不起作用。

如果你想要一个更窄的图形,你应该改变水平尺寸,例如:

plt.figure(..., tight_layout=True, figsize=(12, 5))

这是以英寸为单位,试验数字直到看起来不错。

您还可以使用2乘2的子图来保持正方形图并更好地使用空间:

plt.subplot(2, 2, ...)

虽然这可能看起来不是最理想的数字。