Search code examples
pythonnumpymatplotlibseaborntrendline

How to add trend line and display formula


  1. This is done with a scatter chart. How to operate if it is changed to a line chart?

Is there a function to display the fitting expression in the Seaborn package? 2. code

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')
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)
plt.legend([f"${i}$" for i in (z1_eq, z2_eq)])

Solution

  • I did it this way. This is actually a duplicate question tho. The answer should already be on stackoverflow.

    import numpy as np
    import matplotlib.pyplot as plt
    
    #the plot
    plt.scatter(x, y)
    
    #the trendline    
    z = np.polyfit(x, y, 1)
    p = np.poly1d(z)
    plt.plot(x,p(x),"r--")
    
    plt.show()