Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
786 views
in Technique[技术] by (71.8m points)

matplotlib - how to add legend for scatter()?

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],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 assemble use plot instead 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 to legend, it says

  warnings.warn("Legend does not support %s
Use proxy artist instead.

http://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist
" % (str(orig_handle),))

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...