【问题标题】:Sort a zipped list (string,instances of 'Line2D') by the last character of the string按字符串的最后一个字符对压缩列表(字符串,'Line2D' 的实例)进行排序
【发布时间】:2021-02-25 12:59:12
【问题描述】:

我想在标签中字符串的最后一个字符之后对从 Matplotlib 中的图例中获得的标签列表、句柄进行排序。

到目前为止,我试图结合这个线程: How is order of items in matplotlib legend determined? 用这个线程: How to sort a list by last character of string 不幸的是,这没有用。这是我的代码:

handles, labels = ax.get_legend_handles_labels()

handles, labels = zip(*sorted(zip(labels, handles), key = lambda t:[0]))

leg = ax.legend(handles, labels,loc='best', ncol=2, shadow=True, fancybox=True)

基本上什么都不做。

这里是打印输出:

print(handles)
print(labels)

[<matplotlib.lines.Line2D object at 0x7fd6182ddcd0>, <matplotlib.lines.Line2D object at 0x7fd6182ddb50>, <matplotlib.lines.Line2D object at 0x7fd6448ddc10>, <matplotlib.lines.Line2D object at 0x7fd6448ddf50>, <matplotlib.lines.Line2D object at 0x7fd6609cb790>, <matplotlib.lines.Line2D object at 0x7fd6609cb190>, <matplotlib.lines.Line2D object at 0x7fd660ac5f10>, <matplotlib.lines.Line2D object at 0x7fd660ac5e90>, <matplotlib.lines.Line2D object at 0x7fd619404d10>, <matplotlib.lines.Line2D object at 0x7fd645fcb9d0>]
['Demo_4 maximum', 'Demo_4 mean', 'Demo_5 maximum', 'Demo_5 mean', 'Demo_6 maximum', 'Demo_6 mean', 'Demo_7 maximum', 'Demo_7 mean', 'Demo_8 maximum', 'Demo_8 mean']

【问题讨论】:

    标签: sorting matplotlib zip legend


    【解决方案1】:

    你快到了。该行有一些更正

    handles, labels = zip(*sorted(zip(labels, handles), key = lambda t:[0]))
    
    1. 如果您希望收到handles, labels,,那么您必须以相同的顺序压缩:zip(handles, labels)

    2. 按第一个列表排序的键是lambda t: t[0](注意t)。但是因为我们现在首先有句柄,然后有标签,所以按标签排序,它会是lambda t: t[1](1 是第二个列表,在本例中为标签)

    3. 但是您不想按标签排序,而是按标签的最后一个字符。您可以通过s[-1] 获得字符串s 的最后一个字符。所以,键应该是lambda t: t[1][-1]([1] 因为标签在第二个位置;[-1] 因为你想要每个标签的最后一个字符)。

    所以:

    handles, labels = zip(*sorted(zip(handles, labels), key = lambda t: t[1][-1]))
    

    【讨论】:

    • 非常感谢:)
    猜你喜欢
    • 2015-09-27
    • 2021-01-23
    • 2021-06-10
    • 2014-02-21
    • 2019-01-18
    • 2018-07-02
    • 1970-01-01
    • 2012-07-03
    • 2017-01-27
    相关资源
    最近更新 更多