将趋势线添加到 matplotlib 线图 python [英] Adding a trend line to a matplotlib line plot python
问题描述
抱歉,如果有人问过这个问题,但我在任何地方都找不到答案.我想在plt图上添加一条总体趋势线.样本数据:
将pandas导入为pd数据= pd.DataFrame({'year':[2011,2012,2013,2014,2015,2016,2017,2018,2019],'值': [2, 5, 8, 4, 1, 6, 10, 14, 8]})导入matplotlib.pyplot作为pltplt.rcParams['figure.figsize'] = [28, 26]data.plot(x = "year", y = "value", fontsize = 30)plt.xlabel('时间', fontsize = 30)
如何添加趋势线?
如果您正在寻找简单的线性回归拟合,则可以直接使用
来自文档
<块引用> regplot() 和 lmplot() 函数密切相关,但前者是轴级函数,后者是结合了 regplot() 和 FacetGrid
允许您在不同子图中绘制数据之间的条件关系网格.
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:
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?
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.
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.
这篇关于将趋势线添加到 matplotlib 线图 python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!