matplotlib 绘制 pandas 系列的趋势线

matplotlib plotting trendline for pandas series

我一直在尝试为 pandas 系列绘制趋势线并取得了成功,尽管我得到了多条趋势线,而我期望只有一条。

这是我的代码:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.read_excel( 'cleaned_wind_turbine_data.xlsx' , index_col = 'Date' , parse_dates = True )
df_columns = df.columns.to_list()

df_1 = df.loc[  '2021-02-01 00:00:00' : '2021-02-28 23:50:00' ]

z1 = np.polyfit( df_1['Wind Speed (m/s)'] , df_1['Power ac (kW)'] , 6)
p1 = np.poly1d(z1)

plt.plot( df_1['Wind speed (m/s)'] , df_1['Power ac (kW)'] , 'bx' , 
         df_1['Wind speed (m/s)'] , p1(df_1['Wind speed (m/s)']) , 'r--' ,  markersize = 0.5 , linewidth = 1)
 

我没有收到错误,但我收到了多条趋势线,这是为什么?

您得到了“多条”趋势线,因为您的风速列中有一堆风速顺序混乱。例如,您的风速数组可能类似于

np.array([0.0,5.2,1.0,8.8])

matplotlib 将按顺序在每个点之间画一条线。相反,为了获得最佳拟合线,您需要提出一个等间距的有序 x(类似于 np.array([0.0,0.1,0.2...

这样做

x_trendline = np.arange(df_1['Wind Speed (m/s)'].min(), df_1['Wind Speed (m/s)'].max(), 0.05)
y_trendline = p1(x_trendline)

然后当你绘图时,

plt.plot( df_1['Wind speed (m/s)'] , df_1['Power ac (kW)'] , 'bx' , 
          x_trendline, y_trendline , 'r--' ,  markersize = 0.5 , linewidth = 1)