【问题标题】:How to show labels in Seaborn plots (No handles with labels found to put in legend.)?如何在 Seaborn 图中显示标签(没有发现带有标签的句柄放在图例中。)?
【发布时间】:2019-05-23 20:32:51
【问题描述】:

我尝试使用 seaborn 进行绘图,但标签没有显示,即使它是在轴对象中分配的。

如何在绘图上显示标签?

这是我的代码:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

dx = pd.DataFrame({'c0':range(5), 'c1':range(5,10)})
dx.index = list('abcde')

ax = sns.pointplot(x=dx.index,
                y="c0",
                data=dx, color="r",
                scale=0.5, dodge=True,
                capsize=.2, label="child")
ax = sns.pointplot(x=dx.index,
                y="c1",
                data=dx, color="g",
                scale=0.5, dodge=True,
                capsize=.2, label="teen")
ax.legend()
plt.show()

图例给出错误: No handles with labels found to put in legend.

【问题讨论】:

标签: python matplotlib seaborn


【解决方案1】:

sns.pointplot() 不仅仅用于在同一个图中绘制多个数据框属性,而是用于可视化它们之间的关系,在这种情况下它将生成自己的标签。您可以通过将 labels 参数传递给 ax.legend() 来覆盖它们(请参阅 Add Legend to Seaborn point plot ),但是一旦您对情节进行了更改,很可能会出现一些混乱。

要使用 seaborn 美学制作您的情节,我会这样做:

sns.set_style("white")
fig, ax = plt.subplots()
plt.plot(dx.index, dx.c0, "o-", ms=3,
            color="r", label='child')
plt.plot(dx.index, dx.c1, "o-", ms=3,
            color="g", label='teen')
ax.legend()

结果:

【讨论】:

    【解决方案2】:

    如果您使用seaborn,您应该尝试使用整齐(或“长”)数据而不是“宽”数据。请参阅此链接了解Organizing Datasets

    import numpy as np
    import pandas as pd
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    dx = pd.DataFrame({'c0':range(5), 'c1':range(5,10)})
    dx.index = list('abcde')
    
    # reset the index and melt the remaining columns
    dx1 = dx.reset_index().melt(id_vars='index')
    
    print(dx1)
    
      index variable  value
    0     a       c0      0
    1     b       c0      1
    2     c       c0      2
    3     d       c0      3
    4     e       c0      4
    5     a       c1      5
    6     b       c1      6
    7     c       c1      7
    8     d       c1      8
    9     e       c1      9
    

    您现在可以绘制一次而不是两次

    # modified the "x" and "data" parameters
    # added the "hue" parameter and removed the "color" parameter
    ax = sns.pointplot(x='index',
                    y="value",
                    data=dx1,
                    hue='variable',
                    scale=0.5, dodge=True,
                    capsize=.2)
    
    # get handles and labels from the data so you can edit them
    h,l = ax.get_legend_handles_labels()
    
    # keep same handles, edit labels with names of choice
    ax.legend(handles=h, labels=['child', 'teen'])
    
    plt.show()
    

    编辑

    截至pandas 版本1.1.0pd.melt 具有参数ignore_index,因此我们不必再重置索引。

    import numpy as np
    import pandas as pd
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    dx = pd.DataFrame({'c0':range(5), 'c1':range(5,10)})
    dx.index = list('abcde')
    
    dx = dx.melt(ignore_index=False)
    
    ax = sns.pointplot(x=dx.index,
                    y="value",
                    data=dx, hue="variable",
                    scale=0.5, dodge=True,
                    capsize=.2)
    
    h,l = ax.get_legend_handles_labels()
    
    l = ["child", "teen"]
    
    ax.legend(h, l)
    plt.show()
    

    【讨论】:

      【解决方案3】:

      在您的情况下,ylabel 已设置为 c0,因此不需要图例。

      如果你坚持传说,我建议不要使用sns。相反,尝试使用 pandas 的 matplotlib 接口

      dx = pd.DataFrame({'c0':range(5), 'c1':range(5,10)})
      dx.set_index('c0').plot(marker='o', )
      

      或者直接使用matplotlib的API,更加灵活

      plt.plot(dx.c0, dx.c1, marker='o', label='child')
      plt.legend()
      

      【讨论】:

      • 有没有通用的方法,比如plt.legend()或者ax.legend()
      • 我不熟悉pointplot。我添加了更改标签的代码。
      • @zyxue:“在您的情况下,ylabel 已经设置为 c0,因此不需要图例。”。 ylabellegend 是两个完全不同的东西。
      • @Bazingaa,也许你是对的。我认为在这种特殊情况下没有必要,因为只有一行。
      • 那是另一个问题。但我只是在澄清你的说法。
      【解决方案4】:

      经过一番练习,我找到了使用pandas本身的解决方案,

      dx.plot(kind='line',marker='o',xticks=range(5))
      

      给出情节:

      【讨论】:

        猜你喜欢
        • 2021-10-24
        • 2020-03-20
        • 2020-04-08
        • 1970-01-01
        • 1970-01-01
        • 2021-02-09
        • 1970-01-01
        • 2021-05-25
        • 1970-01-01
        相关资源
        最近更新 更多