首页 文章

使用matplotlib中样本的标签为散点图创建图例

提问于
浏览
3

我在matplotlib中使用散点图来绘制一些点 . 我有两个1D数组,每个数组存储样本的x和y坐标 . 还有另一个1D数组存储标签(以决定应该绘制点的颜色) . 我编程到目前为止:

import matplotlib.pyplot as plt
X = [1,2,3,4,5,6,7]
Y = [1,2,3,4,5,6,7]
label = [0,1,4,2,3,1,1]
plt.scatter(X, Y, c= label, s=50)
plt.show()

现在我希望能够看到哪种颜色与哪个标签相对应?我在matplotlib中查找了传说的实现,如下所示:how to add legend for scatter()?但是他们建议为每个样本标签创建一个图 . 但是我的所有标签都在同一个1D数组(标签)中 . 我怎样才能做到这一点?

1 回答

  • 2

    你可以用colormap来做 . 有关如何操作的一些示例是here .

    import matplotlib.pyplot as plt
    import numpy as np
    import matplotlib.colors as colors
    X = [1,2,3,4,5,6,7]
    Y = [1,2,3,4,5,6,7]
    label = [0,1,4,2,3,1,1]
    
    # Define a colormap with the right number of colors
    cmap = plt.cm.get_cmap('jet',max(label)-min(label)+1)
    
    bounds = range(min(label),max(label)+2)
    norm = colors.BoundaryNorm(bounds, cmap.N)
    
    plt.scatter(X, Y, c= label, s=50, cmap=cmap, norm=norm)
    
    # Add a colorbar. Move the ticks up by 0.5, so they are centred on the colour.
    cb=plt.colorbar(ticks=np.array(label)+0.5)
    cb.set_ticklabels(label)
    
    plt.show()
    

    您可能需要四处寻找以其颜色为中心的刻度标签,但您会明白这一点 .

    enter image description here

相关问题