matplotlib.pyplot:为每个子图使用颜色条时对齐轴标签

matplotlib.pyplot: align axes labels when using a colorbar for each subplot

问题: 我正在使用 matplotlib 创建一个包含多个子图的图形。每个子图都有 x 轴和 y 轴标签,也可能有自己的颜色条。

默认情况下,轴标签位于刻度线旁边(图 1,左)。但是,我希望 y 轴标签垂直对齐(图 1,右)。我正在使用 fig.align_labels() 来执行此操作。

图一:

我想在每个子图中添加颜色条(图 2,左)。但是,当我使用 fig.align_labels() 时,轴标签只是折叠到同一位置(图 2,右)。

图二:

问题:使用颜色条时如何对齐 y 轴标签?

import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import numpy as np

x = np.array(np.arange(5))
y = [np.random.uniform(0.5,2,5)*np.random.random(5)+100,   # <-- 'Long' tick labels
    np.random.uniform(0.5,2,5)*np.random.random(5)+100,    # <-- 'Long' tick labels
    np.random.uniform(0.5,2,5)*np.random.random(5),        # <-- 'Short' tick labels
    np.random.uniform(0.5,2,5)*np.random.random(5)]        # <-- 'Short' tick labels

fig = plt.figure()

for plotnum,yvals in enumerate(y):
    ax = fig.add_subplot(2,2,plotnum+1)
    sc = ax.scatter(x,yvals,c=yvals)
    fig.colorbar(sc, ax=ax)

    ax.set(ylabel=f'Y Values {plotnum}', xlabel=f'X Values {plotnum}')
    ax.yaxis.set_major_formatter(mtick.StrMethodFormatter('{x:,.1f}')) 

plt.tight_layout()
plt.subplots_adjust(wspace=0.8, hspace=0.6)
fig.align_labels()
plt.show()

在代码中处理此问题的最佳方法是在循环过程中添加一行。

fig = plt.figure()

for plotnum,yvals in enumerate(y):
    ax = fig.add_subplot(2,2,plotnum+1)
    sc = ax.scatter(x,yvals,c=yvals)
    fig.colorbar(sc, ax=ax)
    ax.yaxis.set_label_coords(-0.4, 0.5) # update
    ax.set_ylabel(f'Y Values {plotnum}')
    ax.set_xlabel(f'X Values {plotnum}')
    ax.yaxis.set_major_formatter(mtick.StrMethodFormatter('{x:,.1f}')) 

plt.tight_layout()
plt.subplots_adjust(wspace=0.8, hspace=0.6)
#fig.align_ylabels()

plt.show()