【问题标题】:Plot a density function above a histogram在直方图上方绘制密度函数
【发布时间】:2017-10-23 12:18:37
【问题描述】:

在 Python 中,我已经估计了分布模型的密度参数,我想在分布直方图上方绘制密度函数。在 R 中,它类似于使用选项 prop=TRUE

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

# initialization of the list "data"
# estimation of the parameter, in my case, mean and variance of a normal distribution

plt.hist(data, bins="auto") # data is the list of data
# here I would like to draw the density above the histogram
plt.show()

我想最棘手的部分是让它合身。

编辑:我已经根据第一个答案尝试了这个:

mean = np.mean(logdata)
var  = np.var(logdata)
std  = np.sqrt(var) # standard deviation, used by numpy as a replacement of the variance
plt.hist(logdata, bins="auto", alpha=0.5, label="données empiriques")
x = np.linspace(min(logdata), max(logdata), 100)
plt.plot(x, mlab.normpdf(x, mean, std))
plt.xlabel("log(taille des fichiers)")
plt.ylabel("nombre de fichiers")
plt.legend(loc='upper right')
plt.grid(True)
plt.show()

但它不适合图表,如下所示:

** 编辑 2 ** 与直方图函数中的选项 normed=True 一起使用。

【问题讨论】:

  • 不清楚您在寻找什么。您可以添加有关您希望该图形外观的屏幕截图/更多信息吗?与往常一样,Minimal, Complete, and Verifiable Example 将极大地帮助您获得好的答案。
  • 在这里。是的,你是对的,一个例子胜于一千个解释!但我仍然认为我的解释很清楚......
  • 如果您不想使用normed = True,我已经添加了一个解决方案。

标签: python matplotlib statistics


【解决方案1】:

如果我对您的理解正确,您会得到一些数据的均值和标准差。您已经绘制了直方图,并希望在直方图上绘制正态分布线。该行可以使用matplotlib.mlab.normpdf()生成,文档可以在here找到。

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

mean = 100
sigma = 5

data = np.random.normal(mean,sigma,1000) # generate fake data
x = np.linspace(min(data), max(data), 100)

plt.hist(data, bins="auto",normed=True)
plt.plot(x, mlab.normpdf(x, mean, sigma))

plt.show()

给出下图:

编辑:以上仅适用于normed = True。如果这不是一个选项,我们可以定义我们自己的函数:

def gauss_function(x, a, x0, sigma):
    return a * np.exp(-(x - x0) ** 2 / (2 * sigma ** 2))

mean = 100
sigma = 5

data = np.random.normal(mean,sigma,1000) # generate fake data
x = np.linspace(min(data), max(data), 1000)

test = gauss_function(x, max(data), mean, sigma)

plt.hist(data, bins="auto")
plt.plot(x, test)

plt.show()

【讨论】:

    【解决方案2】:

    您要查找的所有内容都已在seaborn 中。

    你只需要使用distplot

    import seaborn as sns
    import numpy as np
    
    data = np.random.normal(5, 2, size=1000)
    sns.distplot(data)
    

    【讨论】:

      猜你喜欢
      • 2012-11-09
      • 1970-01-01
      • 2014-08-20
      • 2017-11-26
      • 1970-01-01
      • 1970-01-01
      • 2021-05-04
      • 2017-06-08
      • 2014-04-10
      相关资源
      最近更新 更多