matplotlib 颜色图 - 预定义到值的映射?

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

我有一个正在使用

imshow()
查看的数组。 (imsave() 确实如此,但过程应该是相同的)。

我知道数组中的值将在 0-9 之间,并且想知道是否可以使用 cmap 将每个输出设置为特定的“颜色”。也许通过将它们映射到字典?

python matplotlib python-2.x
2个回答
5
投票

只需使用

ListedColormap

作为一个快速(但丑陋)的例子:

import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

cmap = ListedColormap(['red', 'green', 'blue', 'black'], 'indexed')

fig, ax = plt.subplots()
im = ax.imshow([range(4)], interpolation='none', cmap=cmap)
fig.colorbar(im)
plt.show()

enter image description here


0
投票

你可以使用这样的东西:

def get_product_number_or_colormap(product=None, get_colormap=False):
    '''
    Get the number of the product or the colormap \\
    If get_colormap is True, return the colormap
    '''
    # Define product families and their corresponding numbers and colors
    product_families = {
        'Other': 'w',  # 'white
        'Semilla de Girasol': 'tab:pink',
        'MAIZ': 'tab:orange',
        'Trigo panificable': 'tab:green',
        'Cebada': 'tab:purple',
        'Urea': 'tab:grey',
        'Yara': 'tab:brown',
        'ACTH': 'tab:green',
        'AXAN': 'tab:red',
        'NAC27': 'tab:blue',
        'SULFAN': 'tab:cyan',
    }
    
    product_families_with_nums = {prod: {'number': num, 'color': product_families[prod]} for num, prod in enumerate(product_families)}
    # print(f"{product_families_with_nums=}")
    
    if get_colormap:
        # convert all colors to a list
        color_list = [product_families[prod] for prod in product_families]
        return colors.ListedColormap(color_list)
    
    # Else: Get the number and color for the product
    try:
        product_number = product_families_with_nums[product]['number']
    except KeyError:
        product_number = 1
        print(f"Product: {product} did not match any of the predefined products")
    
    return product_number 

调用此函数后: 您想要涂漆的表面:

surface[:, surface_size] = get_product_number_or_colormap(product) 

使用你想要的功能:imshow/imsave/pcolormesh (此代码已扩展,因此它也可以与 pcolormesh 一起使用)
您可以使用以下方式获取 cmap:

cmap = get_product_number_or_colormap(get_colormap=True)     
axs.flatten()[i].pcolormesh(x, y, surface, cmap=cmap, alpha=0.7, vmin=0, vmax=7)
© www.soinside.com 2019 - 2024. All rights reserved.