Printing the equation of the best fit line Printing the equation of the best fit line numpy numpy

Printing the equation of the best fit line


So you need to write some function that convert a poly parameters array to a latex string, here is an example:

import pylab as plimport numpy as npx = np.random.randn(100)y = 1 + 2 * x + 3 * x * x + np.random.randn(100) * 2poly = pl.polyfit(x, y, 2)def poly2latex(poly, variable="x", width=2):    t = ["{0:0.{width}f}"]    t.append(t[-1] + " {variable}")    t.append(t[-1] + "^{1}")    def f():        for i, v in enumerate(reversed(poly)):            idx = i if i < 2 else 2            yield t[idx].format(v, i, variable=variable, width=width)    return "${}$".format("+".join(f()))pl.plot(x, y, "o", alpha=0.4)x2 = np.linspace(-2, 2, 100)y2 = np.polyval(poly, x2)pl.plot(x2, y2, lw=2, color="r")pl.text(x2[5], y2[5], poly2latex(poly), fontsize=16)

Here is the output:

enter image description here


Here's a one liner.

If fit is the poly1d object, while plotting the fitted line, just use label argument as bellow,

label='y=${}$'.format(''.join(['{}x^{}'.format(('{:.2f}'.format(j) if j<0 else '+{:.2f}'.format(j)),(len(fit.coef)-i-1)) for i,j in enumerate(fit.coef)]))