matplotlib 如何在一些子情节之间添加空间

sxissh06  于 7个月前  发布在  其他
关注(0)|答案(2)|浏览(57)

如何调整部分子图之间的空白?在下面的示例中,假设我想消除第一和第二子图之间以及第三和第四子图之间的所有空白,并增加第二和第三子图之间的空白?

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()

字符串

kse8i1jr

kse8i1jr1#

为了使解决方案接近您的代码,您可以使用创建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()

字符串


的数据

83qze16e

83qze16e2#

您需要使用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()

字符串


的数据

相关问题