python - Linear Regression: Extending line past data and adding a legend -


i have code:

import math import numpy np import pylab plt1 matplotlib import pyplot plt  uh2 = 1.90866638 uhe = 3.60187307 eh2 = 213.38 ehe = 31.96  r = float(uh2*eh2)/(uhe*ehe)  c_values = [] delta = [] khest = [] j_f21 = [] data = np.genfromtxt("lamda_hehcl.txt", unpack=true);  j_i1=data[1];  j_f1=data[2];  khe=data[7]  data = np.genfromtxt("basecol_basic_new_1.txt", unpack=true);  j_i2=data[0];  j_f2=data[1];  kh2=data[5]  print khe print kh2  khe = map(float, khe) kh2 = map(float, kh2)  khe = np.array(khe) kh2= np.array(kh2)  g = len(kh2)  n in range(0,g):     if j_f2[n] == 1:             jf21 = j_f2[n]         j_f21.append(jf21)         ratio = khe[n]/kh2[n]         c = (((math.log(float(kh2[n]),10)))-(math.log(float(khe[n]),10)))/math.log(r,10)         c_values.append(c)         st = abs(j_f1[n] - j_i1[n])         delta.append(st)  print c_values print delta print j_f21  fig, ax = plt.subplots() ax.scatter(delta,c_values)  i, txt in enumerate(j_f21):     ax.annotate(txt, (delta[i],c_values[i]))  plt.plot(np.unique(delta), np.poly1d(np.polyfit(delta, c_values, 1))(np.unique(delta)))  plt.plot(delta, c_values)  fit = np.polyfit(delta,c_values,1) fit_fn = np.poly1d(fit)  # fit_fn function takes in x , returns estimate y  plt.scatter(delta,c_values, delta, fit_fn(delta)) plt.xlim(0, 12) plt.ylim(-3, 3) 

in code, trying plot linear regression extends past data , touches x-axis. trying add legend plot shows slope of plot. using code, able plot graph.

enter image description here

here trash data have been using try , extend line , add legend code.

x =[5,7,9,15,20] y =[10,9,8,7,6] 

i scatter except linear regression line.

given don't provide data you're loading files unable test this, off top of head:

to extend line past plot, turn line

plt.plot(np.unique(delta), np.poly1d(np.polyfit(delta, c_values, 1))(np.unique(delta))) 

into like

x = np.linspace(0, 12, 50) # both 0 , 12 visually inspecting plot plt.plot(x, np.poly1d(np.polyfit(delta, c_values, 1))(x)) 

but if want line extended x-axis,

polynomial = np.polyfit(delta, c_values, 1) x = np.linspace(0, *np.roots(polynomial)) plt.plot(x, np.poly1d(polynomial)(x)) 

as scatter plot thing, seems me remove line:

plt.plot(delta, c_values) 

oh right, legend, add label plots make, this:

plt.plot(x, np.poly1d(polynomial)(x), label='linear regression') 

and add call plt.legend() before plt.show().


Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -