2011-11-05 99 views
0

這些選項不工作...如何爲scatter()添加圖例?

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

我可以組裝使用,而不是陰謀,寫一個循環,

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

當如果我通過hlegend,它說

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

但是,我怎樣才能得到這個分散的工作,而不寫一個循環?

回答

1

看起來好像你正試圖用實際散點圖填充圖例,或者至少引用散點圖中發生的事情。要創建圖例,您需要將其作爲單獨的實體繪製 - 意味着需要重新創建散點圖形和顏色,例如作爲子圖。這是一個稍微更手動的方法,但應該工作:

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

謝謝 - 我的替代問題是如何手動建立圖例;就是這個。 – hatmatrix