使用 pandas 或 seaborn 通过条形图制作回归线

Making a regression line through a bar char using pandas or seaborn

我是 Pandas 和 Seaborn 的新手,正在努力学习。我想在同一张图上添加趋势线和条形图。我有一些数据看起来像

Year     Sample Size
 2000      500
 2001      3000
 2003      10000
 2004      20000
 2004      23000

我是 pandas 和 seaborn 的新手,我试图通过条形图画一条线来显示减少或增加的趋势,但很难在同一张图表上做到这一点。到现在为止,我有一个条形图。您可以在下面找到代码。

sampleSizes['Sample Size'] -> 是我正在绘制的列。它在 12 年中有大约 12 个值。

plt.figure()
ax = sampleSizes['Sample Size'].plot(kind='bar', title="Trend of Sample Sizes", figsize=(15, 10), legend=True, color = 'grey', fontsize=8)
plt.show()

我正在努力为此添加趋势线。如果有人能指出正确的方向,我将不胜感激。

更新

FinancialYear  Sample Size
   2001         2338
   2002         3171
   2003         2597
   2004         2740
   2005         3447
   2006         3098
   2007         2610
   2008         2819
   2009         2057
   2010         2174
   2011         2709

enter code here

UPDATE2: 使用更新的数据集

In [250]: lr = Ridge()

In [251]: lr.fit(df[['FinancialYear']], df['Sample Size'])
Out[251]:
Ridge(alpha=1.0, copy_X=True, fit_intercept=True, max_iter=None,
   normalize=False, random_state=None, solver='auto', tol=0.001)

In [252]: plt.bar(df['FinancialYear'], df['Sample Size'])
Out[252]: <Container object of 11 artists>

In [253]: plt.plot(df['FinancialYear'], lr.coef_*df['FinancialYear']+lr.intercept_, color='orange')
Out[253]: [<matplotlib.lines.Line2D at 0x171def60>]

结果:


更新:

In [184]: from sklearn.linear_model import Ridge

In [185]: lr = Ridge()

In [186]: lr.fit(df[['Year']], df['Sample Size'])
Out[186]:
Ridge(alpha=1.0, copy_X=True, fit_intercept=True, max_iter=None,
   normalize=False, random_state=None, solver='auto', tol=0.001)

In [187]: plt.bar(df['Year'], df['Sample Size'])
Out[187]: <Container object of 5 artists>

In [188]: plt.plot(df['Year'], lr.coef_*df['Year']+lr.intercept_, color='orange')
Out[188]: [<matplotlib.lines.Line2D at 0x17062898>]

结果:


为此尝试使用 matplotlib 方法:

plt.bar(df['Year'], df['Sample Size'])
plt.plot(df['Year'], df['Sample Size'], '-o', color='orange')

结果: