gpt4 book ai didi

python - 如何在 python 中将误差线添加到直方图

转载 作者:行者123 更新时间:2023-11-28 22:38:47 27 4
gpt4 key购买 nike

您好,我想在这段代码中向直方图添加误差线。我看过一些关于它的帖子,但我没有发现它们有帮助。这段代码产生具有高斯分布的随机数,并对其应用核估计。我需要有误差线来估计直方图在改变带宽时不准确的程度

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com