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

问题描述 投票:9回答:2

我正在尝试绘制具有相同比例的字段。较高的图像值比一个波纹管高10倍,但在imshow中却变成相同的颜色。如何设置两个颜色的刻度相同?

我添加了我正在使用的代码,下面是图片。。

Two imshow plots

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()
python matplotlib plot colorbar imshow
2个回答
8
投票

首先,您需要定义要使用的颜色范围的最小值和最大值。在此示例中,它是您要绘制的两个数组的最小值和最大值。然后使用这些值设置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()

0
投票

为了补充已接受的答案,这里的功能可以制作任意数量的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])
© www.soinside.com 2019 - 2024. All rights reserved.