How do I add a legend for scatter ()?

These options don't 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],c=['k','r','g','r','b'])
plt.legend(loc='upper left')
plt.draw()

ax = plt.axes()
h = ax.scatter(arr[:,0],arr[:,1],c=['k','r','g','r','b'])
plt.legend(h, loc='upper left')
plt.draw()

      

I can put together a usage graph and write a loop,

colors = ['k','r','g','r','b']
ax = plt.axes()
h = []
for i,c in enumerate(colors):
    h.append(ax.plot(arr[i,0],arr[i,1],c+'o'))
plt.legend(colors) ## plt.legend(h,colors) does not work
plt.draw()

      

When, if I pass h

in legend

, he says

  warnings.warn("Legend does not support %s\nUse proxy artist instead.\n\nhttp://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist\n" % (str(orig_handle),))

      

But how can I get this to work scatter without writing a loop?

0


source to share


1 answer


It looks like you are trying to fill the legend with an actual scatter plot, or at least reference what is happening in the scatter plot. To create a legend, you need to draw it as a separate entity - this means that the shapes and colors of the scatter need to be recreated, for example, as a subtitle. 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()

      

+1


source







All Articles