Add legend to chart with data from different columns

Question:

How do I add a legend to a chart where I am showing data from more than one column? The legend isn’t appearing automatically and if I use ax.legend() then I get an error message like this: [WARNING] No artists with labels found to put in legend.

This is what the code looks like:

fig, ax = plt.subplots()
sns.lineplot(x=data.index, y=data[('s', 'a')], color='black', marker='o')
sns.lineplot(x=data.index, y=data[('s', 'f')], color='firebrick', linewidth=1, linestyle='--')
ax.fill_between(x=data.index, y1=data[('s', 'l')], y2=data[('s', 'u')], color='firebrick', alpha=0.2)
ax.legend()

This is what data looks like (using dummy data):

pd.DataFrame(data=[[1,1.1,0.7,1.3],[2,1.9,1.7,2.3],[3,2.8,2.7,3.3]], index=['2022-01-01', '2022-02-01', '2022-03-01'], columns=pd.MultiIndex.from_tuples([('s','a'),('s','f'),('s','l'),('s','u')]))

Not sure what I’m doing wrong but I’d like a legend that shows what the black line, red dotted line and range are.

Asked By: ric

||

Answers:

Add label to your plots like so:

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

data = pd.DataFrame(data=[[1,1.1,0.7,1.3],[2,1.9,1.7,2.3],[3,2.8,2.7,3.3]], index=['2022-01-01', '2022-02-01', '2022-03-01'], columns=pd.MultiIndex.from_tuples([('s','a'),('s','f'),('s','l'),('s','u')]))

fig, ax = plt.subplots()
sns.lineplot(x=data.index, y=data[('s', 'a')], color='black', marker='o', label = "s a")
sns.lineplot(x=data.index, y=data[('s', 'f')], color='firebrick', linewidth=1, linestyle='--', label="s f")
ax.fill_between(x=data.index, y1=data[('s', 'l')], y2=data[('s', 'u')], color='firebrick', alpha=0.2, label="range")
ax.legend()

Output:
enter image description here

Answered By: Michael S.
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.