title: Python fit polynomial, power law and exponential from data
body: <p>I have some data (<code>x</code> and <code>y</code> coordinates) coming from a study and I have to plot them and to find the best curve that fits data. My curves are: </p>
  
  <ul>
  <li>polynomial up to 6th degree; </li>
  <li>power law; </li>
  <li>exponential.</li>
  </ul>
  
  <p>I am able to find the best fit for polynomial with</p>
  
  <pre><code>while(i &lt; 6):
      coefs, val = poly.polyfit(x, y, i, full=True)
  </code></pre>
  
  <p>and I take the degree that minimizes <code>val</code>. </p>
  
  <p>When I have to fit a power law (the most probable in my study), I do not know how to do it correctly. This is what I have done. I have applied the log function to all <code>x</code> and <code>y</code> and I have tried to fit it with a linear polynomial. If the error (val) is lower than the others polynomial tried before, I choose the power law function(naturally if m of the line is negative). Am I correct? </p>
  
  <p>Now how can I reconstruct my power law starting from the line <code>y = mx + q</code> in order to draw it with the original points? I need also to display the function found.</p>
  
  <p>I have tried with:</p>
  
  <pre><code>def power_law(x, m, q):
      return q * (x**m)
  </code></pre>
  
  <p>using</p>
  
  <pre><code>x_new = np.linspace(x[0], x[-1], num=len(x)*10)
  y1 = power_law(x_new, coefs[0], coefs[1])
  popt, pcov = curve_fit(power_law, x_new, y1)
  </code></pre>
  
  <p>but the resulting curve is not fitting the data. </p>