为了理解,我生成了两个2D数组。之后,我绘制该数组的散点图。现在我想绘制线性趋势线以及该线的等式。但我做错了。我真的不知道如何获得方程式。我的代码是:
# Import Libraries
import numpy as np
import matplotlib.pyplot as plt
# Generate Random data
a = np.zeros(shape=(8,8))
a[0] = [1,2,3,4,5,6,7,8]
a[1] = [1,0,3,4,0,6,6,8]
a[2] = [1,2,3,4,5,3,7,8]# Import Libraries
import numpy as np
import matplotlib.pyplot as plt
# Generate Random data
a = np.zeros(shape=(8,8))
a[0] = [1,2,3,4,5,6,7,8]
a[1] = [1,0,3,4,0,6,6,8]
a[2] = [1,2,3,4,5,3,7,8]
a[3] = [1,2,3,0,5,6,7,8]
a[4] = [1,2,3,4,5,6,7,5]
a[5] = [1,2,3,4,5,6,7,8]
a[6] = [1,2,0,1,5,0,8,8]
a[7] = [1,2,3,4,5,6,7,8]
b = np.zeros(shape=(8,8))
b[0] = [1,1,3,4,5,6,7,8]
b[1] = [1,0,3,4,5,6,7,8]
b[2] = [1,2,3,4,5,6,5,6]
b[3] = [2,2,3,0,5,6,7,8]
b[4] = [1,2,3,8,8,6,7,8]
b[5] = [1,2,3,4,5,6,7,9]
b[6] = [1,2,6,4,5,0,7,8]
b[7] = [1,2,3,4,5,6,7,9]
# Draw scatterplot
plt.figure();
plt.title('Scatter plot')
plt.xlabel('a')
plt.ylabel('b')
plt.xlim(0, 10)
plt.ylim(0, 10)
plt.scatter(a, b)
plt.show()
# Add trendline with equation
#z = np.polyfit(a, b, 1)
#p = np.poly1d(z)
#plt.plot(a,p(a),"r--")
#print "y=%.6fx+(%.6f)"%(z[0],z[1]) #Dont know how it comes!
感谢您的帮助和建议!
答案 0 :(得分:0)
以下代码有效:
plt.figure();
plt.suptitle('Scatter plot')
plt.xlabel('a')
plt.ylabel('b')
plt.scatter(a, b)
z = np.polyfit(a.flatten(), b.flatten(), 1)
p = np.poly1d(z)
plt.plot(a,p(a),"r--")
plt.title("y=%.6fx+%.6f"%(z[0],z[1]))
plt.show()
在您的情况下, np.polyfit
需要x
和y
作为1d数组。我把等式(y = coef x + b)作为情节的标题,但你可以随意改变它。
例如,plt.text(8,1,"y=%.6fx+%.6f"%(z[0],z[1]), ha='right')
代替plt.title("y=%.6fx+%.6f"%(z[0],z[1]))
会很好地在图表的右下角打印您的等式(右对齐,坐标为x=8, y=1
)