[英]No legends Seaborn lineplot
When I make a lineplot with Seaborn with multiple lineplots on the same axis, no legends are created.当我使用 Seaborn 在同一轴上制作具有多个线图的线图时,不会创建任何图例。 Even if I supply the argument "brief" or "full" for legend in sns.lineplot, nothing shows, and calling ax.get_legend_handles_labels() returns two empty lists.
即使我在 sns.lineplot 中为图例提供参数“brief”或“full”,也没有任何显示,并且调用 ax.get_legend_handles_labels() 返回两个空列表。
How can I add legends in a box on the right hand side, linking the color of a line to a name?如何在右侧的框中添加图例,将线条的颜色与名称相关联?
import seaborn as sns
import matplotlib.pyplot as plt
import random
fig1 = plt.figure(figsize=(12, 12))
ax = fig1.add_subplot(1, 1, 1)
x = range(10)
series = list()
for i in range(3):
y_i = list()
for j in range(10):
y_i.append(random.randint(0, 50))
sns.lineplot(x=x, y=y_i, ax=ax, legend='brief')
plt.show()
That's because you applied simple lists as x- and y-data.那是因为您将简单列表应用为 x 和 y 数据。 They have no metadata like names or labels.
它们没有名称或标签等元数据。 You can add a label by the
label
-kwarg though, eg:您可以通过
label
-kwarg 添加标签,例如:
sns.lineplot(x=x, y=y_i, ax=ax, legend='brief', label=str(i))
Or you decide to use a pandas series object or a dataframe for your data, which are able to provide column names.或者您决定为您的数据使用 pandas 系列对象或数据框,它们能够提供列名。
You could also add the legend in a separate call, after creating the plot:您还可以在创建绘图后在单独的调用中添加图例:
ax.legend(['label 1', 'label 2', 'label 3'])
It comes useful in situations where you create the lineplot using a 2D array rather than several lists of values in a loop.它在您使用二维数组而不是循环中的多个值列表创建线图的情况下很有用。 In your case, this could look as follows:
在您的情况下,这可能如下所示:
data = np.random.randint(0, 50, size=(10, 3)) # results in 3 lines of length 10 each
sns.lineplot(data=data, ax=ax)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.