JavaScript
x
17
17
1
fig, ax = plt.subplots(figsize = (10,7))
2
sns.lineplot(data = dearborn_1111_groupby,
3
x = 'Date',
4
y = 'Rent',
5
hue = 'generic_type',
6
palette = 'husl',
7
ax = ax).set_title('1111 Dearborn Median In Place Rents (2018 - 2022)')
8
9
sns.lineplot(data = dearborn_1111_groupby,
10
x = 'Date',
11
y = 'Rent_apartlist',
12
color = 'black',
13
ax = ax)
14
15
ax.legend(bbox_to_anchor = (1.15, 0.95), title = 'Unit Type')
16
plt.show()
17
I’m trying to add a legend containing the black line. However the black line is a separate lineplot. How Do I include the black line into the existing legend or a separate legend?
Advertisement
Answer
You can to add a label to the line, via sns.lineplot(..., label=...)
.
Note that when using bbox_to_anchor
for the legend, you also need to set loc=...
. By default, loc='best'
, which change the anchor point depending on small changes in the plot or its parameters. plt.tight_layout()
fits the legend and the labels nicely into the plot figure.
Here is some example code using Seaborn’s flights dataset.
JavaScript
1
22
22
1
import matplotlib.pyplot as plt
2
import seaborn as sns
3
4
flights = sns.load_dataset('flights')
5
fig, ax = plt.subplots(figsize=(12, 5))
6
sns.lineplot(data=flights,
7
x='year',
8
y='passengers',
9
hue='month',
10
palette='husl',
11
ax=ax)
12
sns.lineplot(data=flights,
13
x='year',
14
y='passengers',
15
color='black',
16
label='Black Line',
17
ax=ax)
18
ax.legend(bbox_to_anchor=(1.02, 0.95), loc="upper left", title='Unit Type')
19
ax.margins(x=0)
20
plt.tight_layout()
21
plt.show()
22