pandas 将趋势线添加到 matplotlib 线图 python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/54308172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding a trend line to a matplotlib line plot python
提问by prmlmu
Apologies if this has already been asked but I can't find the answer anywhere. I want to add an overall trend line to a plt plot. Sample data:
抱歉,如果已经有人问过这个问题,但我在任何地方都找不到答案。我想在 plt 图中添加一条整体趋势线。样本数据:
import pandas as pd
data = pd.DataFrame({'year': [2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018,
2019],
'value': [2, 5, 8, 4, 1, 6, 10, 14, 8]})
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = [28, 26]
data.plot(x = "year", y = "value", fontsize = 30)
plt.xlabel('Time', fontsize = 30)
How can I add a trend line?
如何添加趋势线?
回答by Sheldore
If you are looking for a simple linear regression fit, you can use directly either lmplot
or regplot
from seaborn
. It performs the linear regression and plots the fit (line) with a 95% confidence interval (shades, default value). You can also use NumPy to perform the fit. In case you want to use NumPy, comment below and I will update.
如果您正在寻找简单的线性回归拟合,您可以直接使用lmplot
或regplot
from seaborn
。它执行线性回归并绘制具有 95% 置信区间(阴影,默认值)的拟合(线)。您还可以使用 NumPy 来执行拟合。如果你想使用 NumPy,请在下面评论,我会更新。
import seaborn as sns
# Your DataFrame here
# sns.lmplot(x='year',y='value',data=data,fit_reg=True)
sns.regplot(x='year',y='value',data=data, fit_reg=True)
From the Docs
来自文档
The regplot() and lmplot() functions are closely related, but the former is an axes-level function while the latter is a figure-level function that combines regplot() and
FacetGrid
which allows you to plot conditional relationships amongst your data on different subplots in the grid.
regplot() 和 lmplot() 函数密切相关,但前者是轴级函数,而后者是结合 regplot() 的图形级函数,
FacetGrid
它允许您在不同子图上绘制数据之间的条件关系在网格中。