python - 与matplotlib在同一帧上的曲线图和直方图
问题描述
我希望曲线和直方图与 matplotlib 在同一个图上共存。曲线是正态曲线,直方图由数据集制成。我想将直方图(我的样本的实际重新分区)与曲线(如果我有大量数据,我的样本的重新分区应该是什么)进行比较。目标是检查是否存在除危险之外的其他因素。
这是代码:
def testHistogram(arr, mean, variance):
from matplotlib import pyplot as plt
import numpy as np
import scipy.stats as stats
import math
# histogram
num_bins = 100
plt.hist(arr, num_bins, facecolor='yellow', alpha=0.5)
# plot
mu = mean
sigma = math.sqrt(variance)
x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)
plt.plot(x, stats.norm.pdf(x, mu, sigma))
plt.grid(True)
plt.show()
我的问题是,曲线没有出现。(直方图似乎工作正常)。
参数 :
arr
:值列表(我想与曲线比较的样本)mean
: 样本的均值,以建立对应的曲线variance
: 样本的方差,为了建立对应的曲线
编辑:如评论中所问,这是创建参数的方法:
#create a dataset for testing - i am getting it from a database
import random
myList = []
while (i<100):
randomnumber = random.randint(1,100)
myList.append(randomnumber)
i = i+1
#get the mean and variance of the dataset
count = 0
sum = 0
squaresSum = 0
theMean = 0
for onedata in dataset:
count = count+1
sum = sum + onedata
squaressum = squaresSum + onedata*onedata
theMean = sum/count
theVariance = squaresSum/count - theMean*theMean
# launch the function
testHistogram(myList, theMean, theVariance)
解决方案
实际上,您的代码几乎可以正常工作,您只需要对直方图进行归一化即可。scipy.stats.norm返回归一化曲线,即曲线的积分为 1。
在您的情况下,您可能有一条非常低的曲线,几乎在 x 轴上变平,您看不到。
要标准化直方图,只需将参数传递density = True
给hist
函数:
plt.hist(arr, num_bins, density=True, facecolor='yellow', alpha=0.5)
例如,下面的代码(你的小修改):
from matplotlib import pyplot as plt
import numpy as np
import scipy.stats as stats
import math
def testHistogram(arr, mean, variance):
# histogram
num_bins = 100
plt.hist(arr, num_bins, density=True, facecolor='yellow', alpha=0.5)
# plot
mu = mean
sigma = math.sqrt(variance)
x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)
plt.plot(x, stats.norm.pdf(x, mu, sigma))
plt.grid(True)
plt.show()
mm = 100 #norm mean valu
vv = 40 #norm variance
#x is an array of 100 random numbers from the normal distribution
x = np.random.normal(mm, math.sqrt(vv), 100)
testHistogram(x, mm, vv)
绘制下图:
推荐阅读
- javascript - 如何在使用此关键字的方法中设置类变量的状态
- javascript - 如何优雅地防止某些元素在现代浏览器上呈现
- visual-studio-code - VS CODE - 代码运行器 - 输出不工作
- c# - 单元测试控制器抛出异常
- arrays - 如何将 CGPoints 列表转置为 Swift 数组
- python - 当我尝试访问元素的文本时,为什么 Python selenium 会抛出 StaleElementReferenceException?
- angularjs - angularjs单选按钮默认值未选中
- apache - 如何将 https://www.example.com/aaa 重定向到 https://example.com/aaa/
- python - 在不使用任何模块的情况下,在 python 中实现堆栈和队列的最佳方法是什么?
- python - 我尝试将 RK4 实施到 N 体模拟。但是从图中看代码不能正常工作