[Python] Custom colormap in matplotlib using LinearSegmentedColormap not working as expected

Discussão em 'Python' iniciado por Stack, Abril 4, 2025.

  1. Stack

    Stack Membro Participativo

    I have a question about creating my custom colormap in Matplotlib. I start by initializing three colors to represent three points (nodes). Here is the minimal working example code:

    import numpy as np
    import matplotlib as mpl
    from matplotlib.colors import LinearSegmentedColormap

    #define a custom colormap
    nodes = np.array([0, 0.5, 1.0])
    colors = ['black', 'green', 'blue']
    cmap = LinearSegmentedColormap.from_list('', list(zip(nodes, colors)))

    #get the rgba codes for the colors array
    arr_rgba = np.array([mpl.colors.to_rgba(colors[idx]) for idx in range(len(colors))])

    print(cmap(nodes))
    print(arr_rgba)



    I expect cmap(nodes) and arr_rgba to give me the same RGBA codes, since the nodes are where my anchor points are having colors black, green and blue. However, on running this code, the output is:

    >>> print(cmap(nodes))
    array([[0. , 0. , 0. , 1. ],
    [0. , 0.49999231, 0.00392157, 1. ],
    [0. , 0. , 1. , 1. ]])


    and

    >>> print(arr_rgba)
    array([[0. , 0. , 0. , 1. ],
    [0. , 0.50196078, 0. , 1. ],
    [0. , 0. , 1. , 1. ]])


    I know that intermediate points are being interpolated linearly.

    But why at the nodes, do I not get the exact color that I have set up the colormap? Is this the expected behaviour? Any idea?

    Continue reading...

Compartilhe esta Página