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, 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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With