Legend using PathCollections in matplotlib

后端 未结 1 1144
春和景丽
春和景丽 2021-02-15 16:26

I\'m plotting groups of circles using collections and I am not able to generate the legend of the three categories. I want:

  • Cat 1: red circles
  • Cat 2: blue
相关标签:
1条回答
  • 2021-02-15 17:15

    One possible solution is to add Line2D objects to use in the legend, also known as using proxy artists. To achieve this you have to add from matplotlib.lines import Line2D to your script, and then you can replace this code:

    ax.legend(loc = 2)
    plt.colorbar(p)
    
    print p.get_label()
    

    with this:

    circ1 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.4, markersize=10, markerfacecolor="red")
    circ2 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.3, markersize=10, markerfacecolor="blue")
    circ3 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.4, markersize=10, markerfacecolor="yellow")
    
    plt.legend((circ1, circ2, circ3), ("Cat 1", "Cat 2", "Cat 3"), numpoints=1, loc="best")
    

    enter image description here

    0 讨论(0)
提交回复
热议问题