I'm trying to build a sns.FacetGrid
plot using a custom function twin_lineplot()
; but unable to figure out how to "join" the legend labels label1
and label2
.
The below is just a simplified example to demonstrate my problem. I hope to achieve a solution that is scalable (multiple labels in both legends to be combined).
Given the dataset:
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
date_today= datetime.now()
tips = sns.load_dataset("tips")
days = pd.date_range(date_today, date_today + timedelta(tips.shape[0]-1), freq='D')
tips['date'] = days
I would like to plot a sns.FacetGrid()
plot with a legend. However, my attempt below splits the legend to inner plot marked as label2
and outer plot label1
def twin_lineplot(x,y,color,**kwargs):
ax = plt.twinx()
sns.lineplot(x=x,y=y,color=color,**kwargs, ax=ax)
g = sns.FacetGrid(tips, row='smoker', col='time')
g.map(sns.lineplot, 'date', 'tip', color='b', label='label1')
g.map(twin_lineplot, 'date', 'total_bill', color='g', label='label2')
g.add_legend()
g.fig.autofmt_xdate()
plt.show()
How do I combine the two legend labels to be displayed in the outer legend (where label1
is currently shown)?
I would like to scale the solution to solve the below: