Dưới đây là một phương pháp để loại bỏ các mục huyền thoại nhân đôi sau khi đã gán nhãn thường:
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
Và đây là kết quả : Ở bên trái là kết quả của tập lệnh ở trên. Ở bên phải, cuộc gọi chú thích đã được thay thế bằng axes.legend()
.
Lợi thế là bạn có thể đi qua hầu hết mã của mình và chỉ gán nhãn bình thường và không lo lắng về vòng lặp nội tuyến hoặc if
s. Bạn cũng có thể xây dựng này thành một wrapper xung quanh huyền thoại hoặc một cái gì đó như thế.
đây không phải là lỗi, nó đang thêm nhiều mục lặp lại vì nhãn là như nhau. Nếu phải thay đổi nhãn bên trong vòng lặp for ... –
Đây là câu trả lời tuyệt vời cho câu hỏi của bạn: http://stackoverflow.com/questions/13588920/stop-matplotlib-repeating-labels-in-legend –