嗨,我想在这段代码中添加误差条到直方图中。我很少看到关于它的文章,但我没有发现它们有帮助。这段代码生成高斯分布的随机数,并应用核估计。我需要有误差条来估计随着带宽的改变直方图有多不准确
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()
最佳答案
将上面提到的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
关于python - 如何在python中将误差线添加到直方图,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35390276/