【问题标题】:Plot histogram and fit it with exponential fit using python and imported data from excel file绘制直方图并使用 python 和从 excel 文件中导入的数据进行指数拟合
【发布时间】:2021-11-28 14:59:16
【问题描述】:

我正在尝试通过从 excel 文件中导入数据来在 python 中绘制直方图。 此外,直方图需要拟合指数函数。 我该如何做这个绘图和拟合程序?

【问题讨论】:

  • 你能展示一下你到目前为止所做的尝试吗?

标签: python histogram


【解决方案1】:

仅用于绘制 use plt.hist 和您的数据

import random
import matplotlib.pyplot as plt

# data for test
data = [random.randint(1,20) for i in range(20)]

n, x, _ = plt.hist(data)

bin_centers = 0.5*(x[1:]+x[:-1])
plt.plot(bin_centers,n);

对于拟合,您可以提取箱中心并尝试拟合它withcurve_fit

from scipy.optimize import curve_fit

# some exponential function
def func(x, a, b, c):
    return a * np.exp(-b * x) + c

popt, pcov = curve_fit(func, bin_centers, n, bounds=(0, [3., 1., 0.5]))
# bounds are variable, so you can change them as you wish

plt.plot(bin_centers, n, label='data')
plt.plot(bin_centers, func(bin_centers, *popt), label='fit')
plt.legend()

【讨论】:

    猜你喜欢
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    相关资源
    最近更新 更多