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

2023-12-06

我是 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()

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

UPDATE

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

Result:

enter image description here


UPDATE:

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

Result:

enter image description here


尝试使用 matplotlib 方法:

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

Result:

enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 pandas 或 seaborn 通过条形图制作回归线 的相关文章

随机推荐