如何在Seaborn plots中显示标签(找不到标签放在图例中的句柄)?

2024-06-01 22:36:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用seaborn绘制,但是标签没有出现,即使它是在axis对象中指定的。

如何在情节上显示标签?

这是我的代码:

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.


Tags: importdataindexasrangeplt标签ax
3条回答

如果您使用的是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()

plot

在您的例子中,ylabel已经设置为c0,因此不需要图例。

如果你坚持传奇,我建议你不要使用社交网站。相反,尝试使用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()

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

为了利用海本美学创作你的情节,我会这样做:

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()

结果:

enter image description here

相关问题 更多 >