Matplotlib : making a colored markers legend from scratch

后端 未结 2 2125
盖世英雄少女心
盖世英雄少女心 2020-12-05 15:03

In Matplotlib, i\'m trying to make a legend with colored \"markers\" like this one :

this one has been made using the scatter function, but is

2条回答
  •  無奈伤痛
    2020-12-05 15:23

    Following the example given in the legend guide, you can use a Line2D object instead of a marker object.

    The only difference to the example given in the guide is you want to set linestyle='None'

    import matplotlib.lines as mlines
    import matplotlib.pyplot as plt
    
    blue_star = mlines.Line2D([], [], color='blue', marker='*', linestyle='None',
                              markersize=10, label='Blue stars')
    red_square = mlines.Line2D([], [], color='red', marker='s', linestyle='None',
                              markersize=10, label='Red squares')
    purple_triangle = mlines.Line2D([], [], color='purple', marker='^', linestyle='None',
                              markersize=10, label='Purple triangles')
    
    plt.legend(handles=[blue_star, red_square, purple_triangle])
    
    plt.show()
    

提交回复
热议问题