这些选项不起作用......
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()
如果我将h
传递给legend
,则表示
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),))
但是如何在不编写循环的情况下使用散点图来实现这一点?
答案 0 :(得分: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()