Search code examples
pythonmatplotlibseabornfacet-grid

How to sort a FacetGrid legend?


In the image below, how do I sort the legend to show 'No' above 'Yes'? Thanks

import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt

df = sb.load_dataset('tips')
g = sb.FacetGrid(df, col='sex', hue='smoker', col_wrap=2)
g.map(plt.scatter, 'total_bill', 'tip', alpha=.7)
g.axes[-1].legend() 
plt.show()

enter image description here


Solution

  • import seaborn as sns
    import pandas as pd
    import matplotlib.pyplot as plt
    
    df = sns.load_dataset('tips')
    
    # set smoker as categorical and ordered
    df.smoker = pd.Categorical(df.smoker, categories=['No', 'Yes'], ordered=True)
    
    # plot
    g = sns.FacetGrid(df, col='sex', hue='smoker', height=5, col_wrap=2)
    g.map(plt.scatter, 'total_bill', 'tip', alpha=.7)
    g.axes[-1].legend() 
    plt.show()
    

    enter image description here