1

I am trying to apply a shared x-axis on each facet plot with 'total_bill' on the left y-axis, and 'tip' on the right y-axis. Using the tips dataframe to demonstrate.

The following dataset tip is used:

import pandas as pd
import numpy as np
from datetime import datetime, timedelta

date_today= datetime.now()
days = pd.date_range(date_today, date_today + timedelta(tips.shape[0]-1), freq='D')
tips = sns.load_dataset("tips")
tips['date'] = days

Dataset preview:

tips.head()
total_bill tip sex smoker day time size date
0 16.99 1.01 Female No Sun Dinner 2 2021-01-19 16:39:38.363600
1 10.34 1.66 Male No Sun Dinner 3 2021-01-20 16:39:38.363600
2 21.01 3.5 Male No Sun Dinner 3 2021-01-21 16:39:38.363600
3 23.68 3.31 Male No Sun Dinner 2 2021-01-22 16:39:38.363600
4 24.59 3.61 Female No Sun Dinner 4 2021-01-23 16:39:38.363600

I have tried:

g = sns.FacetGrid(tips, row='smoker', col='time')
g.map(sns.lineplot, 'date', 'tip', color='b')
for ax in g.axes.flat:
    ax.twinx()
    for label in ax.get_xticklabels():
        label.set_rotation(60)
g.map(sns.lineplot, 'date', 'total_bill', color='g')
plt.show()

enter image description here

I am unable to figure out the best way to pass the ax.twinx() into the secondary right y-axis plot 'tip'.

What I hope to achieve:

A sns.FacetGrid() with sns.lineplots where the features; 'total_bill' on the left-y-axis, 'tip' on the right-y-axis. A green line represents the 'total_bill' fluctuations, a blue line representing the 'tip' fluctuations to the scale of each respective y-axis feature.

Carl Chang
  • 59
  • 1
  • 6
  • you're going to want to map a custom function that deals with the axes twinning http://seaborn.pydata.org/tutorial/axis_grids.html#using-custom-functions – Paul H Jan 19 '21 at 05:02

1 Answers1

5

You need to create a custom plotting function that create the twin axes and plots the desired output on this newly created axes:

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')
g.map(twin_lineplot, 'date', 'total_bill', color='g')
g.fig.autofmt_xdate()
plt.show()

enter image description here

Diziet Asahi
  • 38,379
  • 7
  • 60
  • 75
  • For the case above, if I included the code `g.add_legend()` and passed labels to `g.map(sns.lineplot, 'date', 'tip', color='b', label='label1')` and `g.map(twin_lineplot, 'date', 'total_bill', color='g', label='label2')` it separately displays the legend for the lines. Any suggestions? https://stackoverflow.com/questions/65819460/normalizing-legend-appearance-when-combining-sns-facetgrid-with-custom-functio – Carl Chang Jan 21 '21 at 02:17