Question

If i have plotted a histogram in python using matplotlib, how can i easily extract the functional form of the histogram, or i suppose, the function of the bestfit curve to the histogram. Im not sure how to plot this bestfit curve. Any help is appreciated, thanks.

The shape of my histogram is like an inverted lennard-jones potential.

Était-ce utile?

La solution

I'm just going to answer both to be thorough. These are two separate problems: fitting a function to your histogram data and then plotting the function. First of all, scipy has an optimization module that you can use to fit your function. Among those curve_fit is probably the easiest.

To give an example,

from scipy.optimize import curve_fit
import numpy as np
import matplotlib.pyplot as plt

# Model function
def f(x, a, b):
    return a * x + b

# Example data
x = np.linspace(0, 10, 20)
y = f(x, 0.2, 3.4) + 0.2 * np.random.normal(size=len(x))

# Do the fit
popt, pcov = curve_fit(f, x, y, [1.0, 1.0])

From curve_fit you get the optimized parameters a, b to your function f and the statistical covariances. You can also pass error for statistical weights as sigma to it.

Now you can plot the data and the histogram. I guess it makes sense to use a higher resolution in x for the curve.

# Plot data
plt.plot(x, y, 'o')

# Plot fit curve
fit_x = np.linspace(0, 10, 200)
plt.plot(fit_x, f(fit_x, *popt))
plt.show()

I haven't specifically dealt with a histogram nor a Lennard-Jones potential here to limit the complexity of the code and focus on the part you asked about. But this example can be adapted to any kind of least squares optimization issue.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top