how to add legend for scatter()?

前端 未结 1 790
旧巷少年郎
旧巷少年郎 2020-12-07 06:28

These options do not work...

import numpy as np
import matplotlib.pyplot as plt

arr = np.random.random((5,3))

ax = plt.axes()
ax.scatter(arr[:,0],arr[:,1],         


        
相关标签:
1条回答
  • 2020-12-07 06:50

    It seems like you are trying to populate the legend with the actual scatter plot, or at least reference what is going on in the scatter plot. To create a legend, you need to draw it as a separate entity - meaning that the scatter point shapes and colors need to be recreated, for example as a subplot. This is a slightly more manual approach but should work:

    colors = ['k','r','g','r','b']
    ax = plt.axes()
    ax.scatter(arr[:,0],arr[:,1],c=['k','r','g','r','b'])
    line1 = plt.Line2D(range(10), range(10), marker='o', color=colors[0])
    line2 = plt.Line2D(range(10), range(10), marker='o',color=colors[1])
    line3 = plt.Line2D(range(10), range(10), marker='o',color=colors[2])
    line4 = plt.Line2D(range(10), range(10), marker='o',color=colors[3])
    line5 = plt.Line2D(range(10), range(10), marker='o',color=colors[4])
    plt.legend((line1,line2,line3, line4, line5),('color1','color2', 'color3', 'color4', 'color5'),numpoints=1, loc=1)
    plt.show()
    
    0 讨论(0)
提交回复
热议问题