pythonmatplotlibsubplottwinx

twinx or twinx-like supylabel for matplotlib subplots?


Given the subplots setup shown below, is there any possibility to add a super y label at the right side of the plot analogously to the 'Green label'?

import matplotlib.pyplot as plt

fig, axs = plt.subplots(2, 2, sharex=True)

axs[0,0].tick_params(axis ='y', labelcolor = 'g')
t = axs[0,0].twinx()
t.tick_params(axis ='y', labelcolor = 'b')

axs[0,1].tick_params(axis ='y', labelcolor = 'g')
axs[0,1].twinx().tick_params(axis ='y', labelcolor = 'b')

axs[1,0].tick_params(axis ='y', labelcolor = 'g')
axs[1,0].twinx().tick_params(axis ='y', labelcolor = 'b')

axs[1,1].tick_params(axis ='y', labelcolor = 'g')
axs[1,1].twinx().tick_params(axis ='y', labelcolor = 'b')


fig.supylabel('Green label', color='g')
plt.tight_layout()

enter image description here


Solution

  • Considering the code in fig.supylabel I think there is no dedicated function and you will have to resort to the fig.text function (which is used internally by fig.supylabel).

    You can reuse and adapt the defaults of the the fig.supylabel function.

    Caveats are that you will not have autopositioning and you will have to adjust the rectangle for the tight_layout.

    ...
    
    def supylabel2(fig, s, **kwargs):
        defaults = {
            "x": 0.98,
            "y": 0.5,
            "horizontalalignment": "center",
            "verticalalignment": "center",
            "rotation": "vertical",
            "rotation_mode": "anchor",
            "size": plt.rcParams["figure.labelsize"],  # matplotlib >= 3.6
            "weight": plt.rcParams["figure.labelweight"],  # matplotlib >= 3.6
        }
        kwargs["s"] = s
        # kwargs = defaults | kwargs  # python >= 3.9
        kwargs = {**defaults, **kwargs}
        fig.text(**kwargs)
    
    
    fig.supylabel("Green label", color="g")
    supylabel2(fig, "Blue label", color="b")
    
    fig.tight_layout(rect=[0, 0, 0.96, 1])
    plt.show()
    

    Resulting plot