【问题标题】:How to convert list of integers to colors on a spectrum and display legend or color spectrum pyplot如何将整数列表转换为光谱上的颜色并显示图例或色谱 pyplot
【发布时间】:2022-01-27 14:37:08
【问题描述】:

我正在尝试将整数列表转换为散点图中点的颜色。我意识到我可以使用颜色图,它可以很好地显示范围内的高值,但我不知道如何创建图例来让我了解它们对应的数值。我正在尝试创建一个函数来创建这个图,它基于真实数据,我期望的值有时会在 0 到 10 的范围内,或者有时可能在 500 到 1000 之间,所以我想要那个显示某种图例色谱。

import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np

list_integers = range(0,100) #the range and variance of this list will vary 
x = range(0,100) 
y = range(0,100)
plt.scatter(x, y, color = cm.rainbow(np.array(list_integers)/np.mean(list_integers)))

【问题讨论】:

    标签: python numpy matplotlib


    【解决方案1】:

    您可以创建自己的legend

    import matplotlib.pyplot as plt
    import matplotlib.cm as cm
    from matplotlib.lines import Line2D
    import numpy as np
    
    list_integers = range(0,100) #the range and variance of this list will vary 
    x = range(0,100) 
    y = range(0,100)
    
    cmap=cm.rainbow(np.array(list_integers)/np.mean(list_integers))
    
    custom_lines = [Line2D([0], [0], color=cmap[i], lw=2) for i in range(len(x))]
    
    fig, ax = plt.subplots()
    ax.scatter(x, y, color=cmap)
    ax.legend(custom_lines, [str(s) for s in x], ncol=5,bbox_to_anchor=(1.1, 1.05))
    

    编辑: 如果您想创建自己的彩条,那么您可以使用我在我的 cmets 中提到的知识(来源:1colorbar34)和ListedColormap

    import matplotlib.pyplot as plt
    import matplotlib.cm as cm
    from matplotlib.lines import Line2D
    import matplotlib.colors
    
    import numpy as np
    
    list_integers = range(0,100) #the range and variance of this list will vary 
    x = range(0,100) 
    y = range(0,100)
    
    # create rgb value mapping
    cmap=cm.rainbow(np.array(list_integers)/np.mean(list_integers))
    # create cmap
    my_cmap = matplotlib.colors.ListedColormap(cmap, name='my_colormap')
    # create norm 
    norm = matplotlib.colors.BoundaryNorm(x, len(x)) 
    
    # create lines for the legend
    custom_lines = [Line2D([0], [0], color=cmap[i], lw=2) for i in range(len(x))]
    
    fig, ax = plt.subplots()
    ax.scatter(x, y, c=cmap, norm=norm)
    ax.legend(custom_lines, [str(s) for s in x], ncol=5,bbox_to_anchor=(1.2, 1.05))
    
    # create the colourbar
    sm = plt.cm.ScalarMappable(cmap=my_cmap, norm=norm)
    plt.colorbar(sm, ticks=np.arange(0,len(x),10))
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-25
    • 2015-10-04
    • 2017-09-16
    • 2019-11-02
    • 2019-05-08
    • 2013-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多