1from scipy import optimize
2
3def piecewise_linear(x, x0, x1, b, k1, k2, k3):
4 condlist = [x < x0, (x >= x0) & (x < x1), x >= x1]
5 funclist = [lambda x: k1*x + b, lambda x: k1*x + b + k2*(x-x0), lambda x: k1*x + b + k2*(x-x0) + k3*(x - x1)]
6 return np.piecewise(x, condlist, funclist)
7
8p , e = optimize.curve_fit(piecewise_linear, x, y)
9
10xd = np.linspace(-30, 30, 1000)
11plt.plot(x, y, "o")
12plt.plot(xd, piecewise_linear(xd, *p))
13
1import pandas as pd
2import numpy as np
3import matplotlib.pyplot as plt
4import statsmodels.formula.api as smf
5
6# plot inline rather than pop out
7%matplotlib inline
8# change the plot size, default is (6, 4) which is a little small
9plt.rcParams['figure.figsize'] = (16, 12)
10
11np.random.seed(9999)
12x = np.random.normal(0, 1, 1000) * 10
13y = np.where(x < -15, -2 * x + 3 , np.where(x < 10, x + 48, -4 * x + 98)) + np.random.normal(0, 3, 1000)
14plt.scatter(x, y, s = 5, color = u'b', marker = '.', label = 'scatter plt')
15plt.show()
16