Trying to show linear regression result on a plot

Question:

I am not sure why simple things can get quite difficult with python. Sorry for this negative intro but I was trying to show a colleague that python works better than Excel and so far I am spending so much time on debugging and figuring out things that I might give up. This is my last hope before giving up. I have a set of data that I am doing linear regression on and would like to display the function.


plt.figure('example')
slope, intercept, r, p, std_err = stats.linregress(values1, values3)

def myfunc(x):
  return slope * x + intercept

mymodel = list(map(myfunc, values1))

plt.scatter(values1, values3)
#plt.plot(values1, mymodel)
#plt.axline([xy1=(0, intercept), slope=slope, label=f'$y = {slope:.1f}x {intercept:+.1f}$'])
#plt.plot(values1, mymodel, 'r', label='y={:.2f}x+{:.2f}'.format(slope,intercept))
plt.plot(values1, mymodel, 'r', label='y={:.2f}x+{:.2f}'.format(slope,intercept))

#plt.axline(xy1, kwargs)

plt.axline
plt.xlabel('time [hh:mm]')
plt.ylabel(desired_value1)
#plt.axline(xy1=(0, intercept), slope=slope, label=f'$y = {slope:.1f}x {intercept:+.1f}$')
plt.show()

I am using Spyder.

Can someone help me figure out why I am not able to show the function. all the commented out codes are the things I tried.

Asked By: K S

||

Answers:

Basing my answer on a recent answer here:

plt.figure()
plt.plot(df["Datetime"], df["Data"])
plt.scatter(xMid, yMid, marker = "x", color = "red")
fit = np.polyfit(xIdx, yMid, 1) # fit
slope, intercept = fit.ravel()
plt.plot(df["Datetime"], np.polyval(fit, df["Datetime"].index), "k--") # plot fit
locator = mdates.AutoDateLocator(minticks = 3, maxticks = 7)
formatter = mdates.ConciseDateFormatter(locator)
plt.gca().xaxis.set_major_locator(locator)
plt.gca().xaxis.set_major_formatter(formatter)
plt.legend(["Raw", "Jumps", f"y={round(slope,1)}x+{round(intercept,1)}"],
          frameon = False)
plt.grid()

This leads to the following:

Plot

What you were missing was a call to the legend and also the necessary adjustment. For more properties, check here

Answered By: Tino D
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.