matplotlib中的图例中有重复项?

2024-05-09 23:59:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图用这个片段将这个传说添加到我的情节中:

import matplotlib.pylab as plt

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')
axes.scatter([e[0] for e in intersections], [e[1] for e in intersections], color='r', label='Intersections')
axes.legend()   

我以这个阴谋告终

enter image description here

显然,这些项目在情节上是重复的。如何更正此错误?


Tags: inimportformatplotlibfigpltlabelcolor
3条回答

正如docs所说,虽然很容易错过:

If label attribute is empty string or starts with “_”, those artists will be ignored.

所以如果我在一个循环中绘制相似的线,并且我只想要图例中的一条示例线,我通常会做如下操作

ax.plot(x, y, label="Representatives" if i == 0 else "")

其中i是我的循环索引。

看起来并不像单独构建它们那么好,但是我经常希望标签逻辑尽可能接近于线图。

(请注意,matplotlib开发人员自己倾向于使用"_nolegend_"来显式地表示。)

下面是一种在正常分配标签后删除重复图例项的方法:

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

结果如下: enter image description here 左边是上面脚本的结果。右边的图例调用已替换为axes.legend()

优点是,您可以遍历大部分代码,只需正常地分配标签,而不必担心内联循环或ifs。您还可以将其构建为legend或类似的包装器。

基于the answer by EL_DON,这里有一个用于绘制没有重复标签的图例的通用方法:

def legend_without_duplicate_labels(ax):
    handles, labels = ax.get_legend_handles_labels()
    unique = [(h, l) for i, (h, l) in enumerate(zip(handles, labels)) if l not in labels[:i]]
    ax.legend(*zip(*unique))

示例用法:open in ^{}

fig, ax = plt.subplots()

ax.plot([0,1], [0,1], c="y", label="my lines")
ax.plot([0,1], [0,2], c="y", label="my lines")

legend_without_duplicate_labels(ax)

plt.show()

enter image description here

相关问题 更多 >