【问题标题】:matplotlib.pyplot: align axes labels when using a colorbar for each subplotmatplotlib.pyplot:为每个子图使用颜色条时对齐轴标签
【发布时间】:2021-11-22 18:20:49
【问题描述】:

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

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

图 1:

我想在每个子图上包含颜色条(图 2,左)。但是,当我使用fig.align_labels() 时,轴标签会简单地折叠到同一位置(图 2,右)。

图 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()

【问题讨论】:

标签: python matplotlib colorbar axes


【解决方案1】:

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

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()

【讨论】:

    猜你喜欢
    • 2019-08-05
    • 1970-01-01
    • 2023-03-14
    • 2011-07-12
    • 2017-11-24
    • 1970-01-01
    • 2015-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多