Polynomial trend line on a group by matplotlib line plot

Viewed 1219

I'm trying to add a polynomial trendline line on a matplotlib groupby line plot. Without messing with the dataframe, is there anyway to achieve the trend line? Thanks in advance!

Score = [1, 2, 3, 4, 5, 6]
Product = ['Apparel', 'Apparel Accessories', 'Footwear', 'Apparel','Footwear','Footwear']
Report = [45,65,45,25,765,23]
format = ['True','True','True','False','True','True']
Country = ['Bangladesh', 'China', 'India', 'Viet Nam', 'China', 'India']
Index = [0.544,0.734,0.763,0.524,0.132,0.625]

dict = {'Score': Score, 'Product': Product, 'Report': Report, 'Format': format, 'Country': Country, 'Index': Index}  

df = pd.DataFrame(dict) 

df 

df.groupby(['Score', 'Product'])['Report'].count()


cnt = ['Bangladesh', 'China', 'India', 'Viet Nam']
sector = ['Apparel', 'Apparel Accessories', 'Footwear']



a4_dims = (11.7, 8.27)
fig, ax = plt.subplots(figsize=a4_dims)
sns.despine(left=False, ax=ax)

df2= df[(df['Country'].isin(cnt)) & (df['Product'].isin(sector))]
df3= df2[df2['Format'] == True]
df3['Format'].value_counts()
# Plot the responses for different events and regions
sns.lineplot(x='Index', y="Score",
#              hue="Country", 
             ax=ax,
             data=df3,
#              trendline="ols",
#              fit_reg=True
            )

plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
1 Answers

You can use seaborn to do a regression plot and mention the order of the fit.

import pandas as pd
import seaborn as sns
df = pd.DataFrame({'x':np.linspace(0,10,20), 'y':(np.linspace(0,10,20)+np.random.random_sample(size=20)*2)**3})
ax = sns.regplot(x='x', y='y', data=df, order=3)
ax.legend(['Polynomial trendline of order 3'])

results in

enter image description here

Related