且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在python中向直方图添加误差线

更新时间:2023-11-30 13:24:58

将上面提到的 answer 与您的代码相结合:

Combining the answer mentioned above with your code:

import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats


def hist_with_kde(data, bandwidth = 0.3):
    #set number of bins using Freedman and Diaconis
    q1 = np.percentile(data, 25)
    q3 = np.percentile(data, 75)

    n = len(data)**(.1/.3)
    rng = max(data) - min(data)
    iqr = 2*(q3-q1)

    bins =int((n*rng)/iqr)
    print(bins)
    x = np.linspace(min(data), max(data), 200)

    kde = stats.gaussian_kde(data, 'scott')

    kde._compute_covariance()
    kde.set_bandwidth()

    plt.plot(x, kde(x), 'r')  # distribution function

    y, binEdges = np.histogram(data, bins=bins, normed=True)
    bincenters = 0.5*(binEdges[1:]+binEdges[:-1])
    menStd = np.sqrt(y)
    width = 0.2
    plt.bar(bincenters, y, width=width, color='r', yerr=menStd)


data = np.random.normal(0, 1, 1000)
hist_with_kde(data, 30)

plt.show()

并查看导入,如 查看全文