简体   繁体   中英

No legends Seaborn lineplot

When I make a lineplot with Seaborn with multiple lineplots on the same axis, no legends are created. 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.

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. They have no metadata like names or labels. You can add a label by the label -kwarg though, eg:

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM