Search code examples
pythonlmfit

Is there a way in lmfit to only show the curve of the fit?


So I wrote some code with the help of lmfit to fit a Gaussian curve on some histogram data. While the curve itself is fine, when I try to plot the results in matplotlib, it displays the fit along with the data points. In reality, I want to plot histogram bars with the curve fit. How do you do this? Or alternatively, is there a way in lmfit to only show the fit curve and then add the histogram plot and combine them together?

Relevant part of my code:

counts, bin_edges = np.histogram(some_array, bins=1000)
bin_widths = np.diff(bin_edges)
x = bin_edges[:-1] + (bin_widths / 2)
y = counts
mod = GaussianModel()
pars = mod.guess(y, x=x)
final_fit = mod.fit(y, pars, x=x)
final_fit.plot_fit()
plt.show()

Here's the graphed result: Gaussian curve


Solution

  • lmfit's builtin plotting routines are minimal wrappers around matplotlib, intended to give reasonable default plots for many cases. They don't make histograms.

    But the arrays are readily available and using matplotlib to make a histogram is easy. I think all you need is:

    import matplotlib.pyplot as plt
    plt.hist(some_array, bins=1000, rwidth=0.5, label='binned data')
    plt.plot(x, final_fit.best_fit, label='best fit') 
    plt.legend()
    plt.show()