def fit_powerlaw(data, plot=True, **kwargs): """Fit a powerlaw by doing a linear regression in log space.""" ys = pd.DataFrame(data) x = pd.Series(data.index.values, index=data.index, dtype=np.float64) values = pd.DataFrame(index=['n', 'A']) fits = {} for col in ys: y = ys[col].dropna() slope, intercept, r, p, stderr = \ stats.linregress(np.log(x), np.log(y)) values[col] = [slope, np.exp(intercept)] fits[col] = x.apply(lambda x: np.exp(intercept) * x**slope) values = values.T fits = pd.concat(fits, axis=1) if plot: from trackpy import plots plots.fit(data, fits, logx=True, logy=True, legend=False, **kwargs) return values
def fit_powerlaw(data, plot=True, **kwargs): """Fit a powerlaw by doing a linear regression in log space.""" ys = pd.DataFrame(data) x = pd.Series(data.index.values, index=data.index, dtype=np.float64) values = pd.DataFrame(index=['n', 'A']) fits = {} for col in ys: y = ys[col].dropna() slope, intercept, r, p, stderr = \ stats.linregress(np.log(x), np.log(y)) values[col] = [slope, np.exp(intercept)] fits[col] = x.apply(lambda x: np.exp(intercept)*x**slope) values = values.T fits = pd.concat(fits, axis=1) if plot: from trackpy import plots plots.fit(data, fits, logx=True, logy=True, legend=False, **kwargs) return values