Dear Stackoverflow users,
How does one show the equation of a trendline made using the python module scipy? Considering that it might not be possible to do that so easily. How can i calculate the slope and intersection point so i can program it myself?
Figure 1: measurement of a yet unknown noise color
import pandas as pd
import matplotlib.pyplot as plt
import TISTNplot as tn
import numpy as np
from scipy import optimize
path = "removed for privacy reasons"
metingen = ['A', 'B', 'C', 'D', 'E', 'F']
"""
Gebruikte kleurcodes behorende bij de geluidskleur
"""
blauw = '#0066ff' # 3dB/octaaf
grijs = '#cbcbcb' # a-weging
roze = '#ff66cc' # -3dB/octaaf
bruin = '#663300' # -6dB/octaaf
violet = '#9900ff' # 6dB/octaaf
wit = '#aa0000' # 0dB/octaaf
zwart = '#000000'
kleur = [blauw, roze, bruin, grijs, violet, wit]
i = 0
meting = metingen[i]
df = pd.read_csv(path+meting+'.txt', sep='\t', header=None, names=['freq', 'intense'], decimal=",")
x = df['freq']
y = df['intense']
x1 = x[df['freq'] < 11][df['freq'] > 8]
y1 = y[df['freq'] < 11][df['freq'] > 8]
print(x1)
plt.plot(x, y, '.', label="Bestand: %s" % metingen[i], color=kleur[i], ms=2)
plt.plot(x1, y1, '.', label="Bestand: %s" % metingen[i], color=kleur[i], ms=5)
"""
Functie voor de trendlijn.
In dit geval een lineaire lijn.
"""
def theorie(x, a, b):
""" x moet een np.array zijn """
return a*x+b
params = [0, 2] # begin waarde voor de fit
params, covariance = optimize.curve_fit(theorie, x1, y1, params)
plt.plot(x, theorie(x, *params), '-b', label='trendlijn', color='red')
"""
Zorgt voor de correcte opmaak
"""
tn.PRECISION_X = 5
tn.PRECISION_Y = 5
tn.fix_axis(plt.gca())
plt.tight_layout()
plt.legend(loc=0)
#plt.xlim(8, 13)
plt.grid()
plt.show()
You're seeing code that reads datafiles. The data has a large uncertainty outside the 8-11 x-axis range. That's why the trend line is fitted in that area.
I'll be happy to receive any feedback on this problem.
Kind regards