pythonmatplotlib

In python subplot get common ylabel for each column


Can someone help me to plot using matplotlib of having subplots as shown in below code. I need ylabel for each column and common xlabel. Is it possible to use twinx or make grids.

import matplotlib.pyplot as plt
fig, ax = plt.subplots(4, 2, sharex = True)
fig.subplots_adjust(hspace=0)
ax[0][0] = plt.subplot(4, 2, 1)
ax[1][0] = plt.subplot(4, 2, 3)
ax[2][0] = plt.subplot(4, 2, 5)
ax[3][0] = plt.subplot(4, 2, 7)
ax[0][1] = plt.subplot(4, 2, 2)
ax[1][1] = plt.subplot(4, 2, 4)
ax[2][1] = plt.subplot(4, 2, 6)
ax[3][1] = plt.subplot(4, 2, 8)

for ax in fig.get_axes():
    ax.label_outer()
ax9 = fig.add_subplot(111, frameon=False)
plt.tick_params(labelcolor='none', which='both', top=False, bottom=False, left=False, right=False)
plt.xlabel('xlabel')
plt.ylabel('ylabel')
ax9.xaxis.set_label_coords(0.5, -0.07)
plt.show()

When I run this code I get this plot: enter image description here

whereas I need this kind of plot: enter image description here


Solution

  • You could use subfigures and set the supylabel for each separately, e.g.,

    import matplotlib.pyplot as plt
    
    fig = plt.figure()
    
    subfigs = fig.subfigures(1, 2)
    
    axleft = subfigs[0].subplots(4, 1, sharex=True, gridspec_kw=dict(hspace=0))
    axright = subfigs[1].subplots(4, 1, sharex=True, gridspec_kw=dict(hspace=0))
    
    for ax in axright:
        ax.set_yticklabels([])
    
    subfigs[0].supylabel("y label 1", x=-0.05)
    subfigs[1].supylabel("y label 2", x=0.00)
    
    fig.supxlabel("x label")
    

    enter image description here

    Note that you may have to play around with the image size or supylabel's x position argument to prevent overlapping with the tick labels.