【问题标题】:Avoid duplicate labels in matplotlib with x, y of form [[...], [...] ...]避免 matplotlib 中 x, y 形式为 [[...], [...] ...] 的重复标签
【发布时间】:2022-01-11 08:55:45
【问题描述】:

首先,让我将link 发布到类似的帖子中,但略有不同。

我无法使用表单输入数据创建具有唯一标签的图例:

    idl_t, idl_q = [[0, 12, 20], [8, 14, 24]], [[90, 60, 90], [90, 60, 90]]

绘制如下:

    plt.plot(idl_t, idl_q, label="Some label")

结果是我有多个相同文本的标签。之前发布的链接在使用格式数据时遇到类似问题:

idl_t, idl_q = [1,2], [2,3]

这与我的情况不同,我不确定那里的逻辑是否可以应用于我的情况

所以问题是如何在不更改数据输入的情况下避免重复标签?

【问题讨论】:

    标签: python matplotlib graph visualization


    【解决方案1】:

    可以在一行中完成,但恐怕它看起来不太好。

    fig, ax = plt.subplots()
    for i, (x, y) in enumerate(zip(zip(*idl_t), zip(*idl_q))):
        ax.plot(x, y, label="Label" if i == 0 else "_nolabel_")
    
    

    也许这样的东西更容易理解:

    for i in range(len(idl_t)):
        ax.plot(
            [xval[i] for xval in idl_t], 
            [yval[i] for yval in idl_q],
            label="Label" if i == 0 else "_nolabel_"
        ) 
    
    ax.legend()
    

    如果您想用[90, 60, 90] 绘制[0, 12, 20],用[90, 60, 90] 绘制[8, 14, 24]:

    for i, (x, y) in enumerate(zip(idl_t, idl_q)):
        ax.plot(x, y, label="Label" if i == 0 else "_nolabel_")
    
    ax.legend()
    plt.show()
    

    【讨论】:

    • 我正在绘制线 x: idl_t[0][i] 到 idl_t[1][i] ,其中 y = idl_q[0][i] 到 idl_q[1][i]。跨度>
    【解决方案2】:

    您可以获取用于制作图例的句柄和标签并对其进行修改。在下面的代码中,这些标签/句柄被制作成一个字典,该字典保留了唯一的字典键(与您的标签相关联),从而导致丢失重复的标签。 (您可能希望以不同的方式操纵它们以实现您的目标。)

    import matplotlib.pyplot as plt
    
    idl_t, idl_q = [[0, 12, 20], [8, 14, 24]], [[90, 60, 90], [90, 60, 90]]
    plt.plot(idl_t, idl_q, label="Some label")
    
    # get legend handles and their corresponding labels
    handles, labels = plt.gca().get_legend_handles_labels()
    
    # zip labels as keys and handles as values into a dictionary, ...
    # so only unique labels would be stored 
    dict_of_labels = dict(zip(labels, handles))
    
    # use unique labels (dict_of_labels.keys()) to generate your legend
    plt.legend(dict_of_labels.values(), dict_of_labels.keys())
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2020-07-06
      • 2023-04-04
      • 2018-09-07
      • 2020-07-23
      • 1970-01-01
      • 2013-09-01
      • 1970-01-01
      • 2018-08-01
      • 1970-01-01
      相关资源
      最近更新 更多