简体   繁体   English

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

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

I am trying to plot to fields with the same scale.我正在尝试绘制具有相同比例的字段。 The upper image values are a 10 times higher than the one bellow, but they turn out to be the same color in the imshow.上面的图像值比下面的值高 10 倍,但它们在 imshow 中的颜色相同。 How can I set both to have the same scales in colours?如何将两者设置为具有相同的颜色比例?

I added the code I am using bellow the image..我在图像下方添加了我正在使用的代码..

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

First you need to define the min and max of the color range you want to use.首先,您需要定义要使用的颜色范围的最小值和最大值。 In this example it is the min and max of both arrays you are plotting.在此示例中,它是您正在绘制的两个数组的最小值和最大值。 Then use these values to set the range of the imshow color code.然后使用这些值来设置 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()

To compliment the accepted answer, here is a function that can make an arbitrary number of imshow plots that all share the same color map:为了赞美接受的答案,这里有一个函数可以制作任意数量的 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()

Usage:用法:

show_fields([field1,field2,field3])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM