Skip to main content
 首页 » 编程设计

python之将趋势线添加到 matplotlib 线图 python

2025年05月04日20bhlsheji

如果有人问过这个问题,我深表歉意,但我无法在任何地方找到答案。我想在 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) 

如何添加趋势线?

请您参考如下方法:

如果您正在寻找简单的线性回归拟合,您可以直接使用 lmplot或 regplot来自 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)  

来自文档

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.