how to put equations of 2 trendlines in Python

Viewed 32

I have taken 2 sets of data in the under same set of conditions, and that I have taken the data I put the trendlines for the respective data group, but how do I show their equations? I know how to do only for one, and I put that for the title. If anyone has some other optimal solution, it would be very helpful. Thanks!

So far, this is what I've done:

x1 = np.array([1,2,3,4,6,7,8,9])
y1 = np.array([0.5, 0.6, 1, 1.25, 1.5, 1.7, 1.8, 2.1])
xerr = 0.0
yerr = 0.1

x2 = np.array([1,2,3,4,6,7,8,9])
y2 = np.array([2.25, 2.2, 2.4, 2.75, 2.7, 2.9, 3.2, 3.2])

z1 = np.polyfit(x1,y1,1)
p1 = np.poly1d(z1)

z2 = np.polyfit(x2,y2,1)
p2 = np.poly1d(z2)

plt.errorbar(x1,y1, xerr = xerr, yerr = yerr, fmt = 'ok')
plt.plot(x1,p1(x1), 'r--')
plt.errorbar(x2,y2, xerr = xerr, yerr = yerr, fmt = 'oc')
plt.plot(x2,p2(x2), 'b--')
plt.xlabel('x')
plt.ylabel('y')
plt.title('y1=%.6fx+%.6f'%(z1[0],z1[1]))
1 Answers

You might consider using sympy, for example:

from sympy import S, symbols, printing

x = symbols("x")
z1_poly = sum(S(f"{v:.2f}") * x ** i for i, v in enumerate(z1[::-1]))
z1_eq = printing.latex(z1_poly)
z2_poly = sum(S(f"{v:.2f}") * x ** i for i, v in enumerate(z2[::-1]))
z2_eq = printing.latex(z2_poly)

Then show it as a legend (and give it a proper title instead).

plt.legend([f"${i}$" for i in (z1_eq, z2_eq)])

Output:

plot1

Related