CPB*_*PBL 49 python matplotlib legend
我不得不重新订购传奇中的物品,当时我不认为我应该这样做.我尝试:
from pylab import *
clf()
ax=gca()
ht=ax.add_patch(Rectangle((1,1),1,1,color='r',label='Top',alpha=.01))
h1=ax.bar(1,2,label='Middle')
hb=ax.add_patch(Rectangle((1,1),1,1,color='k',label='Bottom',alpha=.01))
legend()
show()
Run Code Online (Sandbox Code Playgroud)
最终以中上方为底.我怎样才能得到正确的订单?它不是由创建顺序决定的吗?

更新:以下内容可用于强制执行订单.我认为这可能是最简单的方法,这看起来很尴尬.问题是什么决定了原始订单?
hh=[ht,h1,hb]
legend([ht,h1.patches[0],hb],[H.get_label() for H in hh])
Run Code Online (Sandbox Code Playgroud)
kev*_*vin 65
这是一个快速片段,用于对图例中的条目进行排序.它假定您已经添加了带有标签的绘图元素,例如,类似的东西
ax.plot(..., label='label1')
ax.plot(..., label='label2')
Run Code Online (Sandbox Code Playgroud)
然后主要位:
handles, labels = ax.get_legend_handles_labels()
# sort both labels and handles by labels
labels, handles = zip(*sorted(zip(labels, handles), key=lambda t: t[0]))
ax.legend(handles, labels)
Run Code Online (Sandbox Code Playgroud)
这只是对http://matplotlib.org/users/legend_guide.html中列出的代码的简单修改
Ian*_*cks 25
在其他一些aswers略有变化.列表order应与图例项目的长度相同,并手动指定新订单.
handles, labels = plt.gca().get_legend_handles_labels()
order = [0,2,1]
plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
Run Code Online (Sandbox Code Playgroud)
以下函数使图例顺序的控制变得容易和可读。
您可以通过标签指定所需的顺序。它将找到图例句柄和标签,删除重复的标签,并根据给定的列表 ( order)对它们进行排序或部分排序。所以你像这样使用它:
reorderLegend(ax,['Top', 'Middle', 'Bottom'])
Run Code Online (Sandbox Code Playgroud)
详情如下。
# Returns tuple of handles, labels for axis ax, after reordering them to conform to the label order `order`, and if unique is True, after removing entries with duplicate labels.
def reorderLegend(ax=None,order=None,unique=False):
if ax is None: ax=plt.gca()
handles, labels = ax.get_legend_handles_labels()
labels, handles = zip(*sorted(zip(labels, handles), key=lambda t: t[0])) # sort both labels and handles by labels
if order is not None: # Sort according to a given list (not necessarily complete)
keys=dict(zip(order,range(len(order))))
labels, handles = zip(*sorted(zip(labels, handles), key=lambda t,keys=keys: keys.get(t[0],np.inf)))
if unique: labels, handles= zip(*unique_everseen(zip(labels,handles), key = labels)) # Keep only the first of each handle
ax.legend(handles, labels)
return(handles, labels)
def unique_everseen(seq, key=None):
seen = set()
seen_add = seen.add
return [x for x,k in zip(seq,key) if not (k in seen or seen_add(k))]
Run Code Online (Sandbox Code Playgroud)
更新形式的函数cpblUtilities.mathgraph位于https://gitlab.com/cpbl/cpblUtilities/blob/master/mathgraph.py
用法是这样的:
fig, ax = plt.subplots(1)
ax.add_patch(Rectangle((1,1),1,1,color='r',label='Top',alpha=.1))
ax.bar(1,2,label='Middle')
ax.add_patch(Rectangle((.8,.5),1,1,color='k',label='Bottom',alpha=.1))
legend()
reorderLegend(ax,['Top', 'Middle', 'Bottom'])
show()
Run Code Online (Sandbox Code Playgroud)
可选unique参数确保删除具有相同标签的重复绘图对象。
根据 Ian Hincks 的回答,图例元素顺序的更改可以通过嵌套列表理解在一行中完成。这避免了命名中间变量的需要并减少了代码重复。
plt.legend(*(
[ x[i] for i in [2,1,0] ]
for x in plt.gca().get_legend_handles_labels()
), handletextpad=0.75, loc='best')
Run Code Online (Sandbox Code Playgroud)
我在最后添加了一些额外的参数来说明plt.legend()不需要单独调用该函数来格式化和排序元素。