setting a legend matching the colours in pyplot.scatter

后端 未结 3 1599
迷失自我
迷失自我 2021-01-07 07:03

Suppose my data is organized in the following way:

x_values = [6.2, 3.6, 7.3, 3.2, 2.7]
y_values = [1.5, 3.2, 5.4, 3.1, 2.8]
colours = [1, 1, 0, 1, -1]
label         


        
3条回答
  •  情书的邮戳
    2021-01-07 07:24

    You can always make your own legend as follows:

    import matplotlib.pyplot as plt
    import matplotlib.patches as mpatches
    
    x_values = [6.2, 3.6, 7.3, 3.2, 2.7]
    y_values = [1.5, 3.2, 5.4, 3.1, 2.8]
    
    a = 'red'
    b = 'blue'
    c = 'yellow'
    
    colours = [a, a, b, a, c]
    labels = ["a", "a", "b", "a", "c"]
    
    axis = plt.gca()
    axis.scatter(x_values, y_values, c=colours)
    
    # Create a legend
    handles = [mpatches.Patch(color=colour, label=label) for label, colour in [('a', a), ('b', b), ('c', c)]]
    plt.legend(handles=handles, loc=2, frameon=True)
    
    plt.show()
    

    Which would look like:

提交回复
热议问题