将两个 matplotlib imshow 图设置为具有相同的颜色图比例

Set two matplotlib imshow plots to have the same color map scale

我正在尝试绘制相同比例的字段。上面的图像值比下面的图像值高 10 倍,但在 imshow 中它们的颜色相同。如何将两者设置为具有相同的颜色比例?

我在图片下方添加了我正在使用的代码..

def show_field(field1,field2):
    fig = plt.figure()
    ax = fig.add_subplot(2, 1, 1)
    ax.imshow(field1,cmap=plt.cm.YlGn)
    ax.set_adjustable('box-forced')
    ax.autoscale(False)
    ax2 = fig.add_subplot(2, 1, 2)
    ax2.set_adjustable('box-forced')
    ax2.imshow(field2,cmap=plt.cm.YlGn)
    ax2.autoscale(False)
    plt.show()

首先您需要定义要使用的颜色范围的最小值和最大值。在此示例中,它是您正在绘制的两个数组的最小值和最大值。然后使用这些值来设置 imshow 颜色代码的范围。

import numpy as np     
def show_field(field1,field2):

    combined_data = np.array([field1,field2])
    #Get the min and max of all your data
    _min, _max = np.amin(combined_data), np.amax(combined_data)

    fig = plt.figure()
    ax = fig.add_subplot(2, 1, 1)
    #Add the vmin and vmax arguments to set the color scale
    ax.imshow(field1,cmap=plt.cm.YlGn, vmin = _min, vmax = _max)
    ax.set_adjustable('box-forced')
    ax.autoscale(False)
    ax2 = fig.add_subplot(2, 1, 2)
    ax2.set_adjustable('box-forced')
    #Add the vmin and vmax arguments to set the color scale
    ax2.imshow(field2,cmap=plt.cm.YlGn, vmin = _min, vmax = _max)
    ax2.autoscale(False)
    plt.show()

为了赞美接受的答案,这里有一个函数可以制作任意数量的 imshow 图,它​​们都共享相同的颜色图:

def show_fields(fields):
    combined_data = np.array(fields)
    #Get the min and max of all your data
    _min, _max = np.amin(combined_data), np.amax(combined_data)

    fig = plt.figure()
    for i in range(len(fields)):
        ax = fig.add_subplot(len(fields), 1, i+1)
        #Add the vmin and vmax arguments to set the color scale
        ax.imshow(fields[i],cmap=plt.cm.YlGn, vmin = _min, vmax = _max)
        ax.set_adjustable('box-forced')
        ax.autoscale(False)

    plt.show()

用法:

show_fields([field1,field2,field3])