修改我的代码-插入更改值的更好方法

问题描述 投票:0回答:1

我有一个构建散点图并显示线性回归趋势线和R平方的代码。我通过计算斜率,截距和r_value来手动计算R平方,如下所示:

#Try for Linear Regression Moddel- still couldn't display anything on any scatter plot.
x = merged_data['NDVI']
y = merged_data['nitrogen']

from scipy.stats import linregress

slope, intercept, r_value, p_value, std_err = linregress(x, y)
print('slope:',slope)
print('intercept:',intercept)
print('R:',r_value)
print('R^2:',(r_value**2))  

## Create Figure (empty canvas)
fig = plt.figure()
##Add set of axes to figure
axes = fig.add_axes([1,1,1,1]) # left, bottom, width, height (range 0 to 1)

##plot
plt.scatter(x,y,alpha=0.5)
plt.title('NDVI vs Nitrogen 17/6/2019')
plt.xlabel('NDVI')
#here I insert the calculted value manually according to the print values
plt.figtext(1.8,1.6, "y=-7.269X+10.11")
plt.figtext(1.8,1.55, "R^2=-0.017")
plt.ylabel('Nitrogen')
plt.show()

我有很多不同的数据库,我想为它们检查,并且我不想每次在绘图中进行测试时都需要手动更改,因此我可以告诉python自动获取这些值并将其放在正确的位置吗? ?

python pandas scipy linear-regression
1个回答
0
投票

希望鼓舞人心的格式示例:

plt.figtext(1.8,1.6, "y={0}X+{1}".format(slope, intercept))
plt.figtext(1.8,1.55, "R^2={}".format(r_value**2)

您可以根据需要进一步定制示例。

© www.soinside.com 2019 - 2024. All rights reserved.