将泊松分布拟合到数据(直方图+线)

Fit poisson distribution to data (histogram + line)

我需要做的正是@interstellar 在这里问的 但是在 R 环境中(不是 matlab)。

所以,我用我的观察值创建了一个条形图,我只需要在上面拟合泊松分布。

这是我的数据:

df = read.table(text = 'Var1 Freq     
    6    1
    7    2
    8    5
    9    7
   10    9
   11    6
   12    4
   13    3
   14    2
   15    1', header = TRUE)

创建的条形图如下:

t = barplot(df$Freq, ylim = c(0,10))
axis(1, at=t, labels=df$Var1)

我还是 R 的新手,所以如何使用 fitdist 函数或其他功能在条形图上方创建一条线?

任何帮助将不胜感激。

更新

我已经解决了一些问题,但我不确定 100% 是否正确:

#create barplot
t = barplot(df$Freq, ylim = c(0,10))
axis(1, at=t, labels=df$Var1)

#find lambda value from my data
pois = fitdist(df$Freq, 'pois', method = 'mle')
print(pois)

#result
Fitting of the distribution ' pois ' by maximum likelihood 
Parameters:
       estimate Std. Error
lambda        4  0.6324555

#create 10 values from a real poisson distribution
dist = dpois(1:10, lambda = 4)

#multiply them by `sum(df$Freq)` in order to scale them to the barplot
dist = dist * sum(df$Freq)

#add the line plot to the original barplot
lines(dist, lwd = 2)

result

然而,曲线并不平滑..

 #fit poisson distr to tbl$Freq data
poisson = fitdist(df$Freq, 'pois', method = 'mle')
print(poisson)

#plot
plot(df$Var1, df$Freq, type = 'h', ylim = c(0,10), ylab = 'No. of years with x events', 
     xlab = 'No. of events in a year', main = 'All 13-day events with Poisson')


dist = dpois(1:10, lambda = 4)
dist = dist * sum(df$Freq)
dist = as.data.frame(dist)
dist$Var1 = df$Var1

lines(dist$Var1, dist$dist, lwd = 2)

vcd 附带 goodfit() 函数,它基本上完全按照您的要求进行:通过 ML 拟合模型,然后可视化观察到的和拟合的频率。默认情况下,采用平方根标度以更好地显示较低预期频率的偏差。此外,默认情况下,条形图悬挂在曲线上以对齐轴上的所有偏差。此版本称为 rootogram(有关详细信息,请参阅我们最近在 The American Statistician 中的讨论)。虽然可以更改默认值以获得原始比例的常设条形图:

gf <- goodfit(df[, 2:1], "poisson")
plot(gf, type = "standing", scale = "raw")
plot(gf, type = "hanging", scale = "sqrt")                    

注意: 另请注意,在您的代码版本中,您获得的 MLE 恰好是 4,因为您只是在估计中使用了 $Freq,但是不是 $Var1。我的代码版本假设您的数据意味着对 6 进行 1 次观察,对 7 进行 2 次观察,等等。如果这不是您的意思,则可能需要调整代码。