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

14

我想画两个具有相同比例的场。上面的图像值比下面的高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()

2
你正在寻找 vminvmax 参数。 (另外提一句,这是一个重复的问题,但我目前找不到规范版本...) - Joe Kington
是的,我也没有找到这个问题,尽管我确信它已经被提出很多次了... - Ohm
我相当肯定有比我标记为重复的问题更精确的副本... 如果你或其他任何人遇到它,请随意更改! - Joe Kington
1
嗯,我无法使用正确的重复问题重新关闭它,但这里有一个更精确的重复问题:https://dev59.com/enA75IYBdhLWcg3wS3BA#3376734 - Joe Kington
@JoeKington 那你觉得呢,我应该删除我的问题吗? - Ohm
不,不要删掉它。这是一个好问题,重复也没有什么问题。实际上,保留(已关闭的)重复问题更好,因为搜索的人有更高的机会找到他们的答案(例如,有人可能正在搜索与您的问题标题非常相似的内容,并找到这个问题)。 - Joe Kington
2个回答

19

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

1
我不想将两个非常大的矩阵连接起来得到“combined_data”,所以我只是做了“_min = min(field1.min(), field2.min())”。 - jds

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接