首页 > 解决方案 > 与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()

我的问题是,曲线没有出现。(直方图似乎工作正常)。

参数 :

编辑:如评论中所问,这是创建参数的方法:

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

标签: pythonpython-3.xmatplotlibplot

解决方案


实际上,您的代码几乎可以正常工作,您只需要对直方图进行归一化即可。scipy.stats.norm返回归一化曲线,即曲线的积分为 1。
在您的情况下,您可能有一条非常低的曲线,几乎在 x 轴上变平,您看不到。

要标准化直方图,只需将参数传递density = Truehist函数:

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)

绘制下图:

在此处输入图像描述


推荐阅读