Search code examples
seabornscatter-plotjointplot

Joint plot with regression line and classes by hue


I have the following dataframe

df = pd.DataFrame({
    'Product': ['AA', 'AA', 'BB', 'BB', 'AA', 'AA', 'BB', 'BB'],
    'Sales': [ 200, 100, 400, 100, 300, 100, 200, 500], 
    'Price': [ 5, 3, 3, 6, 4, 7, 4, 1]})

I would like to plot the regression line of the overall data, but also the scatter points by hue (in this case by Product) in the same chart.

I can get the regression line by:

g = sns.jointplot(y='Sales', x='Price', data=df, kind='reg', scatter = False)

And I can get the scatter by:

g = sns.scatterplot(y='Sales', x='Price', data=df, hue='Product')

But there are two different charts. Anyway that I can combine the two commands?


Solution

  • You have to tell the scatterplot in which axis object you want to plot. Options for a seaborn jointplot are the main plot area ax_joint or the two minor plot areas ax_marg_x and ax_marg_y.

    from matplotlib import pyplot as plt
    import seaborn as sns
    import pandas as pd
    
    df = pd.DataFrame({
        'Product': ['AA', 'AA', 'BB', 'BB', 'AA', 'AA', 'BB', 'BB'],
        'Sales': [ 200, 100, 400, 100, 300, 100, 200, 500], 
        'Price': [ 5, 3, 3, 6, 4, 7, 4, 1]})
    
    g = sns.jointplot(y='Sales', x='Price', data=df, kind='reg', scatter = False)
    
    sns.scatterplot(y='Sales', x='Price', data=df, hue="Product", ax=g.ax_joint)
    
    plt.show()
    

    Sample output: enter image description here