Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

enter image description here

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()
like image 734
Simen Russnes Avatar asked Apr 30 '19 07:04

Simen Russnes


2 Answers

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, e.g.:

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.

like image 71
SpghttCd Avatar answered Oct 05 '22 13:10

SpghttCd


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)
like image 38
mysh Avatar answered Oct 05 '22 14:10

mysh