

Вот мой код:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# Define the power law function
def power_law(x, factor, exponent):
'''
x: x axis data
factor: y axis intersection
exponent: slope
'''
return factor * x ** exponent
# Define the power-law function
# Generate synthetic data following a power-law distribution
np.random.seed(0) # for reproducibility
x_data = np.linspace(1, 10, 50) # example x values
y_data = power_law(x = x_data, factor = 0.2, exponent = -10) * (1 + np.random.normal(scale=0.1, size=len(x_data))) # example y values with added noise
# Fit the power-law model to the data
params, covariance = curve_fit(power_law, x_data, y_data)
# Extract fitted parameters
fac_fit, exp_fit = params
# Plot the data and the fitted power-law curve
plt.figure()
plt.scatter(x_data, y_data, label = 'Data')
plt.plot(x_data, power_law(x_data, fac_fit, exp_fit), color='red', label='Fitted Power Law')
plt.xscale('log')
plt.yscale('log')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Fitting a Power Law to Data')
plt.legend()
plt.grid(True)
plt.show()
# Print the fitted parameters
print("Fitted Parameters:")
print("factor =", fac_fit)
print("exponent =", exp_fit)
# My data
x_data = freq_full_ordered_withM[mask]
y_data = PSD_full_ordered_withM[mask]
# Filter out non-positive values from x_data and corresponding y_data
positive_mask = x_data > 0
x_data = x_data[positive_mask]
y_data = y_data[positive_mask]
# Fit the power-law model to the data
params, covariance = curve_fit(power_law, x_data, y_data)
# Extract fitted parameters
fac_fit, exp_fit = params
# Plot the data and the fitted power-law curve
plt.figure()
plt.scatter(x_data, y_data, label = 'Data')
plt.plot(x_data, power_law(x_data, fac_fit, exp_fit), color='red', label='Fitted Power Law')
plt.xscale('log')
plt.yscale('log')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Fitting a Power Law to Data')
plt.legend()
plt.grid(True)
plt.show()
Источник: https://stackoverflow.com/questions/781 ... nly-the-st