我编写了代码以创建散点图并获得线性趋势线方程,但是pyplot不会将趋势线直接放在散点图上。
这里是代码(很麻烦!):
for acc in accdict:
cc = 'b'
zz = 50
if str(accdict\[acc\]\[0\]) in str(alt):
cc = 'r'
for item in accdict\[acc\]\[1\]:
altx.append(float(item))
for item in accdict\[acc\]\[2\]:
alty.append(float(item))
if altcount < refcount:
zz = 100
else:
zz = 0
else:
for item in accdict\[acc\]\[1\]:
refx.append(float(item))
for item in accdict\[acc\]\[2\]:
refy.append(float(item))
plt.scatter(accdict\[acc\]\[1\], accdict\[acc\]\[2\], color=cc, zorder=zz)
#plt.plot(np.unique(altx), np.poly1d(np.polyfit(altx, alty, 1))(np.unique(altx)), color='r',zorder=zz)
(m,b) = np.polyfit(altx ,alty ,1)
p = np.poly1d((m,b))
plt.plot(altx, p(altx), color='r', zorder=z)
yp = np.polyval(\[m,b\], altx)
alteq = phen + ' = ' + str(round(m, 4)) + 'x' ' + ' + str(round(b, 4))
plt.plot(np.unique(refx), np.poly1d(np.polyfit(refx, refy, 1))(np.unique(refx)), color='b', zorder=zz)
(m,b) = np.polyfit(refx ,refy ,1)
yp = np.polyval(\[m,b\], refx)
refeq = phen + ' = ' + str(round(m, 4)) + 'x' ' + ' + str(round(b, 4))
plt.annotate(' ' + alteq, xy=(0.5, 0), xytext=(0, 10), xycoords=('axes fraction', 'figure fraction'), textcoords='offset points', size=8, ha='left', va='bottom', color='r')
plt.annotate(refeq + ' ',xy=(0.5, 0), xytext=(0, 10), xycoords=('axes fraction', 'figure fraction'), textcoords='offset points', size=8, ha='right', va='bottom', color='b')
plt.xlabel('Days')
plt.ylabel(phen)
red_patch = mpatches.Patch(color='red', label='Alt')
blue_patch = mpatches.Patch(color='blue', label='Ref')
plt.legend(handles=\[red_patch,blue_patch\],loc='best')
plt.title('Position:'+sheetname+' '+phen+' Over Time')
newpath = '/Users/elijahsaltzman/'+filename\[:-4\]+'-scatter/'+sheetname
if not os.path.exists(newpath):
os.makedirs(newpath)
plt.savefig(newpath + '/' + phen + '.png')
plt.close()