代码之家  ›  专栏  ›  技术社区  ›  maaland

将axhline添加到图例中

  •  2
  • maaland  · 技术社区  · 6 年前

    我正在使用seaborn从数据帧创建一个线形图,我想在该图中添加一条水平线。这很好,但我在为图例添加水平线时遇到问题。

    以下是一个最小的、可验证的示例:

    import seaborn as sns
    import matplotlib.pyplot as plt
    import numpy as np
    import pandas as pd
    
    x = np.array([2, 2, 4, 4])
    y = np.array([5, 10, 10, 15])
    isBool = np.array([True, False, True, False])
    
    data = pd.DataFrame(np.column_stack((x, y, isBool)), columns=["x", "y", "someBoolean"])
    print(data)
    
    ax = sns.lineplot(x="x", y="y", hue="someBoolean", data=data)
    
    plt.axhline(y=7, c='red', linestyle='dashed', label="horizontal")
    
    plt.legend(("some name", "some other name", "horizontal"))
    
    plt.show()
    

    incorrect plot

    “某个名称”和“某个其他名称”的图例显示正确,但“水平”图例只是空白。我试着简单地使用 plt.legend() 但是图例由数据集中看似随机的值组成。

    有什么想法吗?

    1 回复  |  直到 6 年前
        1
  •  10
  •   DavidG    6 年前

    简单使用 plt.legend() 告诉您正在打印哪些数据:

    enter image description here

    您正在使用 someBoolean 就像色调一样。因此,您实际上是通过对数据应用布尔掩码来创建两行。一行表示假值(在上面的图例中显示为0),另一行表示真值(在上面的图例中显示为1)。

    为了获得所需的图例,需要设置控制柄和标签。您可以使用 ax.get_legend_handles_labels() . 然后确保省略第一个句柄,如上图所示,该句柄没有艺术家:

    ax = sns.lineplot(x="x", y="y", hue="someBoolean", data=data)
    
    plt.axhline(y=7, c='red', linestyle='dashed', label="horizontal")
    
    labels = ["some name", "some other name", "horizontal"]
    handles, _ = ax.get_legend_handles_labels()
    
    # Slice list to remove first handle
    plt.legend(handles = handles[1:], labels = labels)
    

    这使得:

    enter image description here