是否有 matplotlib.pyplot 代码可以在没有 'axes.grid' 代码的情况下允许三个子图?

Is there a matplotlib.pyplot code that can allow three subplots without the 'axes.grid' code?

我正在尝试获得一组看起来像此代码结果的子图:

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

fig = plt.figure(tight_layout=True)
gs = gridspec.GridSpec(2, 2)

ax = fig.add_subplot(gs[0, :])
ax.plot(np.arange(0, 1e6, 1000))
ax.set_ylabel('YLabel0')
ax.set_xlabel('XLabel0')

for i in range(2):
    ax = fig.add_subplot(gs[1, i])
    ax.plot(np.arange(1., 0., -0.1) * 2000., np.arange(1., 0., -0.1))
    ax.set_ylabel('YLabel1 %d' % i)
    ax.set_xlabel('XLabel1 %d' % i)
    if i == 0:
        for tick in ax.get_xticklabels():
            tick.set_rotation(55)
fig.align_labels()  # same as fig.align_xlabels(); fig.align_ylabels()

plt.show()

我想知道是否有替代此代码而无需使用 matplotlib.gridspec 而完全使用 matplotlib.pyplot 的替代方法,以便我可以获得该结果。

我最初尝试了以下代码的多种变体:

plt.subplot(111)
plt.plot(I_123, nu_123, 'o', markersize=5)
plt.plot(I_123, F_123)
plt.grid(True)
plt.xlabel('Current/A', size='15')
plt.ylabel('Frequency/Hz', size='15')
plt.title('Plot for all plot points', size='25')

plt.subplot(221)
plt.plot(B_glycerine, nu_glycerine, 'o', markersize=5, color='indigo')
plt.plot(B_glycerine, Fglyc, color='red')
plt.grid('True')
plt.tick_params(labelsize='20')
plt.xlabel('Magnetic Field Strength/T', size='24')
plt.ylabel(r'Frequency/$\timesMHz', size='24')
plt.title('NMR plot for glycerine', size='25')

plt.subplot(222)
plt.plot(B_ptfe, nu_ptfe, 'o', markersize=5, color='indigo')
plt.plot(B_ptfe, Fptfe, color='red')
plt.grid('True')
plt.tick_params(labelsize='20')
plt.xlabel('Magnetic Field Strength/T', size='24')
plt.ylabel(r'Frequency/$\timesMHz', size='24')
plt.title('NMR plot for PTFE', size='25')

但我一直只看到两个子图,其中一个子图总是完全被排除在外,而且没有找到任何纠正方法。我不想使用第一段代码,因为它可能导致我不得不更改其余代码以使其对我有意义,所以如果有任何其他使用 matplotlib.pyplot 的方法,那将不胜感激。

如果你想要相同的轴配置,你可以这样做:

plt.subplot(211)
(...)
plt.subplot(223)
(...)
plt.subplot(224)
(...)

gs = gridspec.GridSpec(2, 2)

ax1 = plt.subplot(gs[0,:])
(...)
ax2 = plt.subplot(gs[1,0])
(...)
ax3 = plt.subplot(gs[1,1])
(...)

或者您可以用切片指定范围:

ax1 = plt.subplot(2, 2, (1, 2))
ax2 = plt.subplot(2, 2, 3)
ax3 = plt.subplot(2, 2, 4)

这有利于使用相同的网格规范,因此 constrained_layout 将继续工作。