基于matplotlib线图的群上多项式趋势线

2024-04-29 15:01:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在matplotlib groupby line图上添加一条多项式趋势线。 在不影响数据框架的情况下,是否仍有实现趋势线的方法? 提前谢谢

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.)

Tags: reporttrueformatdfindexproductaxcountry
1条回答
网友
1楼 · 发布于 2024-04-29 15:01:20

您可以使用seaborn绘制回归图并说明拟合顺序

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'])

导致

enter image description here

相关问题 更多 >