ここでは、すでに正常にラベルを割り当てた後、重複凡例エントリを削除する方法です:
representatives=[[[-100,40],[-50,20],[0,0],[75,-5],[100,5]], #made up some data
[[-60,80],[0,85],[100,90]],
[[-60,15],[-50,90]],
[[-2,-2],[5,95]]]
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1)
axes.set_xlabel('x (m)')
axes.set_ylabel('y (m)')
for i, representative in enumerate(representatives):
axes.plot([e[0] for e in representative], [e[1] for e in representative],color='b', label='Representatives')
#make sure only unique labels show up (no repeats)
handles,labels=axes.get_legend_handles_labels() #get existing legend item handles and labels
i=arange(len(labels)) #make an index for later
filter=array([]) #set up a filter (empty for now)
unique_labels=tolist(set(labels)) #find unique labels
for ul in unique_labels: #loop through unique labels
filter=np.append(filter,[i[array(labels)==ul][0]]) #find the first instance of this label and add its index to the filter
handles=[handles[int(f)] for f in filter] #filter out legend items to keep only the first instance of each repeated label
labels=[labels[int(f)] for f in filter]
axes.legend(handles,labels) #draw the legend with the filtered handles and labels lists
そして、ここでは結果があります: 左は上記のスクリプトの結果です。右側では、伝言通話はaxes.legend()
に置き換えられています。
利点は、ほとんどのコードを通り、通常はラベルを割り当て、インラインループやif
を心配する必要がないことです。また、これを凡例などのラッパーに組み込むこともできます。
これはエラーではありません。ラベルが同じであるため、多くの繰り返しエントリが追加されています。 forループ内のラベルを変更する必要がある場合は... –
ここにあなたの質問に対する素晴らしい答えがあります:http://stackoverflow.com/questions/13588920/stop-matplotlib-repeating-labels-in-legend –