1

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?

postcolonialist
  • 449
  • 7
  • 17

2 Answers2

3

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

Mr. T
  • 11,960
  • 10
  • 32
  • 54
1

To extend on Mr. T's answer, you could also do something like this to keep the kde marginal plots of the jointplot:

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, hue="Product", alpha=0.5, xlim=(0.5,7.5), ylim=(-50, 550))
g1 = sns.regplot(y='Sales', x='Price', data=df, scatter=False, ax=g.ax_joint)
regline = g1.get_lines()[0]
regline.set_color('red')
regline.set_zorder(5)
plt.show()

enter image description here

tycl
  • 338
  • 2
  • 4