如何在python中添加误差条到直方图

时间:2016-02-14 09:31:49

标签: python python-3.x numpy matplotlib scipy

嗨我想在此代码中为柱状图添加误差条。我看过很少关于它的帖子但是我没有发现它们有用。这段代码产生具有高斯分布的随机数,并且内核估计适用于它。我需要有错误栏来估计直方图通过改变带宽而不准确的程度

from random import * 
import numpy as np 
from matplotlib.pyplot import* 
from matplotlib import* 
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()


    plot(x,kde(x),'r') # distribution function
    hist(data,bins=bins,normed=True) # histogram

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

show()

3 个答案:

答案 0 :(得分:2)

将上述answer与您的代码结合使用:

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()

MaxNoe

所述,请查看导入

答案 1 :(得分:2)

你可以这样做:

import numpy as np
import matplotlib.pyplot as plt

plt.style.use('ggplot')

data = np.random.normal(size=10000)

# plt.hist gives you the entries, edges 
# and drawables we do not need the drawables:
entries, edges, _ = plt.hist(data, bins=25, range=[-5, 5])

# calculate bin centers
bin_centers = 0.5 * (edges[:-1] + edges[1:])

# draw errobars, use the sqrt error. You can use what you want there
# poissonian 1 sigma intervals would make more sense
plt.errorbar(bin_centers, entries, yerr=np.sqrt(entries), fmt='r.')

plt.show()

结果: enter image description here

答案 2 :(得分:0)

这看似重复:Matplotlib histogram with errorbars

即。你必须使用matplotlib.bar()来获取错误栏

在您的示例中,您将看起来像这样: 你可以替换

hist(data,bins=bins,normed=True)

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

玩弄参数,直到找到你喜欢的东西:)

相关问题