pythonmatplotlibsubplotmatplotlib-gridspec

How can I have subplots without using axes.grid?


I am trying to attain a set of subplots that looks like the result for this 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()

I was wondering whether there was an alternative to this code without having to use matplotlib.gridspec and instead wholly use matplotlib.pyplot so that I can have that result.

I initially tried a lot of variations of the code below:

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/$\times$10MHz', 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/$\times$10MHz', size='24')
plt.title('NMR plot for PTFE', size='25')

but I only keep on seeing two subplots with one subplot always completely excluded and without finding any method of correcting this. I do not want to use the first piece of code because it may cause me to have to change the rest of my code to make it make sense for me, so if there is any other way of using matplotlib.pyplot instead, that will be appreciated.


Solution

  • Or you can specify the range with a slice:

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

    This has the benefit of using the same gridspec and hence constrained_layout will continue to work.