python - 我有一个由 numpy 数组组成的图形,包括五个折线图,如何为每个图形添加趋势线?
问题描述
我正在使用一个数据库,该数据库的相关数据被加载到一个 numpy 数组中。使用以下代码,我制作了一个包含五个变量的五行图。
porosity = 0.35
df_plot = df_soilTemp[['Moisture litter layer','Moisture 3 cm','Moisture 20 cm','Moisture 50 cm','Moisture 100 cm']]/porosity
np_soilTemp = np.asarray(df_soilTemp)
t = np.asarray(df_soilTemp.index)
df_plot['Moisture litter layer'].where((df_plot['Moisture litter layer']>0.03) & (df_plot['Moisture litter layer']<1.0),
np.nan,inplace=True)
df_plot['Moisture 3 cm'].where((df_plot['Moisture 3 cm']>0.03) & (df_plot['Moisture 3 cm']<1.0), np.nan,inplace=True)
df_plot['Moisture 20 cm'].where((df_plot['Moisture 20 cm']>0.03) & (df_plot['Moisture 20 cm']<1.0), np.nan,inplace=True)
df_plot['Moisture 50 cm'].where((df_plot['Moisture 50 cm']>0.03) & (df_plot['Moisture 50 cm']<1.0), np.nan,inplace=True)
df_plot['Moisture 100 cm'].where((df_plot['Moisture 100 cm']>0.03) & (df_plot['Moisture 100 cm']<1.0), np.nan,inplace=True)
f4 = df_plot.iplot(asFigure=True, layout=dict(yaxis=dict(title='Soil moisture content (m3/m3) '),
xaxis=dict(title='Time (years) '),
title='Soil moisture variability over time at different soil depths',
legend_title='Soil depth'), width=2)
f4.show()
我想为每个变量添加一条趋势线,我该怎么做?
我试过这样的事情:
df_soilTemp_MA=df_soilTemp.rolling(window=17520).mean()
slope,intercept,r_val,p_val,error =linregress(df_soilTemp_MA['Moisture litter layer'])
print(slope)
我希望这会给我五行之一的趋势线,但我收到了这个错误:
IndexError Traceback (most recent call last)
<ipython-input-19-a26336926e7a> in <module>
12
13 df_soilTemp_MA=df_soilTemp.rolling(window=17520).mean()
---> 14 slope,intercept,r_val,p_val,error =linregress(df_soilTemp_MA['Moisture litter layer'])
15 print(slope)
16
~\anaconda3\lib\site-packages\scipy\stats\_stats_mstats_common.py in linregress(x, y)
123 if x.shape[0] == 2:
124 x, y = x
--> 125 elif x.shape[1] == 2:
126 x, y = x.T
127 else:
IndexError: tuple index out of range
任何帮助是极大的赞赏!如果相关,我在 Jupyter Notebook 工作,因为我使用的数据是在线的。
解决方案
linregress 正在获取 2 个参数:x 和 y 或二维数组,可以溢出到 2。您似乎只传递了 1 个参数,这是一个 Pandas 系列,其中一些值我猜是您想要查看的“y”。所以我的建议是你添加为“x”:np.arange(len(df_soilTemp_MA['Moisture litter layer'])) 这只是 0,1,2…,len - 1。