title: How to make trend line go through the origin while plotting its R2 value - python
body: <p>I am working with a dataframe <code>df</code> which looks like this:</p>
  <pre class="lang-py prettyprint-override"><code>index       var1      var2      var3
  0           0.0       0.0       0.0 
  10          43940.7   2218.3    6581.7
  100         429215.0  16844.3   51682.7
  </code></pre>
  <p>I wanted to plot each variable, plot their trend line forced to the origin, calculate and plot the R2 value.</p>
  <p>I kind of found what I wanted in <a href="https://stackoverflow.com/questions/41635448/how-can-i-draw-scatter-trend-line-on-matplot-python-pandas">this post</a> however the trend line doesn't go through the origin and I can't find a way to make it work.</p>
  <p>I tried to manually modify the values of the first point of the trend line but the result doesn't seem good.</p>
  <pre class="lang-py prettyprint-override"><code>for var in df.columns[1:]:
      fig, ax = plt.subplots(figsize=(10,7))
      
      x = df.index
      y = df[var]
      
      z = numpy.polyfit(x, y, 1)
      p = numpy.poly1d(z)
      pylab.plot(x,p(x),&quot;r--&quot;)
      
      plt.plot(x,y,&quot;+&quot;, ms=10, mec=&quot;k&quot;)
      z = np.polyfit(x, y, 1)
      y_hat = np.poly1d(z)(x)
      y_hat[0] = 0     ###--- Here I tried to replace the first value with 0 but it doesn't seem right to me.
  
      plt.plot(x, y_hat, &quot;r--&quot;, lw=1)
      text = f&quot;$y={z[0]:0.3f}\;x{z[1]:+0.3f}$\n$R^2 = {r2_score(y,y_hat):0.3f}$&quot;
      plt.gca().text(0.05, 0.95, text,transform=plt.gca().transAxes, fontsize=14, verticalalignment='top')
      
  </code></pre>
  <p>Is there any way of doing it? Any help would be greatly appreciated.</p>