matlibplot:如何在一些子图之间添加空格

use*_*229 4 matplotlib

如何调整某些子图之间的空白?在下面的示例中,假设我想消除第 1 个和第 2 个子图之间以及第 3 个和第 4 个之间的所有空白,并增加第 2 个和第 3 个之间的空间?

import matplotlib.pyplot as plt
import numpy as np

# Simple data to display in various forms
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

f, ax = plt.subplots(4,figsize=(10,10),sharex=True)

ax[0].plot(x, y)
ax[0].set_title('Panel: A')

ax[1].plot(x, y**2)

ax[2].plot(x, y**3)
ax[2].set_title('Panel: B')
ax[3].plot(x, y**4)

plt.tight_layout() 
Run Code Online (Sandbox Code Playgroud)

Imp*_*est 6

为了使解决方案接近您的代码,您可以使用创建 5 个子图,中间的一个是其他图的四分之一,然后删除中间的图。

import matplotlib.pyplot as plt
import numpy as np

# Simple data to display in various forms
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

f, ax = plt.subplots(5,figsize=(7,7),sharex=True, 
                     gridspec_kw=dict(height_ratios=[4,4,1,4,4], hspace=0))

ax[0].plot(x, y)
ax[0].set_title('Panel: A')

ax[1].plot(x, y**2)

ax[2].remove()

ax[3].plot(x, y**3)
ax[3].set_title('Panel: B')
ax[4].plot(x, y**4)


plt.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


Y. *_*Luo 5

您需要使用GridSpec在图之间有不同的空间:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np

# Simple data to display in various forms
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

f = plt.figure(figsize=(10,10))
gs0 = gridspec.GridSpec(2, 1)

gs00 = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=gs0[0], hspace=0)
ax0 = f.add_subplot(gs00[0])
ax0.plot(x, y)
ax0.set_title('Panel: A')
ax1 = f.add_subplot(gs00[1], sharex=ax0)
ax1.plot(x, y**2)

gs01 = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=gs0[1], hspace=0)
ax2 = f.add_subplot(gs01[0])
ax2.plot(x, y**3)
ax2.set_title('Panel: B')
ax3 = f.add_subplot(gs01[1], sharex=ax0)
ax3.plot(x, y**4)

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明