【问题标题】:draw CDF by reading values from file : matplotlib通过从文件中读取值来绘制 CDF:matplotlib
【发布时间】:2018-09-26 19:12:30
【问题描述】:

我需要绘制从文件中读取的整数值的 cdf。我正在关注示例here。我不确定如何规范化 pdf 的数据,然后计算 cdf。

import numpy as np
from pylab import *

with open ("D:/input_file.txt", "r+") as f:
    data = f.readlines()
    X = [int(line.strip()) for line in data]
    Y  = exp([-x**2 for x in X])  # is this correct? 

    # Normalize the data to a proper PDF
    Y /= ... # not sure what to write here

    # Compute the CDF
    CY = ... # not sure what to write here

    # Plot both
    plot(X,Y)
    plot(X,CY,'r--')

    show()

【问题讨论】:

  • 你能分享你的输入数据吗?
  • 88 93 184 91 107 170 88 107 167 90
  • CDF是累积分布函数吗?
  • 是的,还有总和为 1 的 pdf。

标签: python matplotlib cdf


【解决方案1】:

我可以提出一个答案,您可以在其中使用 NumPy 确定概率密度函数 (PDF) 和累积分布函数 (CDF)。

import numpy as np
# -----------------
data = [88,93,184,91,107,170,88,107,167,90];
# -----------------
# get PDF:
ydata,xdata = np.histogram(data,bins=np.size(data),normed=True);
# ----------------
# get CDF:
cdf = np.cumsum(ydata*np.diff(xdata));
# -----------------
print 'Sum:',np.sum(ydata*np.diff(xdata))

我正在使用 Numpy 方法直方图,它会给我 PDF,然后我将从 PDF 计算 CDF。

【讨论】:

  • 如何从这里绘制 pdf 和 cdf? plt.plot(xdata,ydata) 抛出错误:x and y must have same first dimension, but have shapes (11L,) and (10L,)
  • 是的,它们的大小不同,因为 xdata 大 1。这与 np.histogram 方法相关联,该方法对于 x 坐标给出了条形的开始和结束坐标。如果你想用绘图绘制图形,我会使用起点和终点的中心点。基本上是xplot = 0.5*(xdata[0:-1]+xdata[1:])plot(xplot,ydata)
  • 这个数字现在似乎要出来了,但我认为沿 y 轴的 pdf 值不正确。它们似乎低于正确的。例如如果 data = [70,70,90,90] ,则 x = 70 的 y 轴值应为 0.5,x = 90 的值应为 0.5,但图表将 x = 70 和 90 的 pdf 值显示为 0.1。
  • 是的,你是对的。值 0.1 是规范值,例如dy/dx 的值。如果你想得到 0.5 的值,你必须将它乘以 dx,即 ydata*np.diff(xdata)。或者简单地使用关键字normed=False 并将ydata 标准化为数据的大小,即ydata,xdata = np.histogram(data,bins=np.size(data),normed=True);ydata = ydata/np.size(data)。希望这会有所帮助。
猜你喜欢
  • 1970-01-01
  • 2018-04-28
  • 1970-01-01
  • 2020-08-14
  • 2013-10-15
  • 1970-01-01
  • 2021-10-04
  • 2015-05-30
  • 1970-01-01
相关资源
最近更新 更多