%poissonness plot (hoaglin)
clear all
close all
 disp('Goodness of Fit: Poissonness Plot')
 lw = 2; 
 set(0, 'DefaultAxesFontSize', 16);
 fs = 15;
 msize = 8;

rand('state',2)
N = 50000;  xx = poissrnd(4, 1, N); %similate N Poisson(4) rv's.
% observed frequencies
ni  =   [sum(xx==0) sum(xx==1) sum(xx==2) sum(xx==3)  sum(xx==4) ... 
         sum(xx==5) sum(xx==6) sum(xx==7) sum(xx==8)  sum(xx==9) ...
    sum(xx==10) sum(xx==11) sum(xx==12) sum(xx==13)  sum(xx==14)]' ;

 i=(0:14)'
 poissonness = log(ni) + log(factorial(i)) - log(N);
 
figure(1)
 plot(i, log(4)*i - 4,'r:','LineWidth',lw) %theoretical line with lambda = 4
 hold on
 plot(i, poissonness,'ko','LineWidth',lw, ...
 'MarkerEdgeColor','k', 'MarkerFaceColor','g','MarkerSize',msize);
set( get( gca, 'XLabel' ), 'Interpreter', 'latex' ); 
set( get( gca, 'YLabel' ), 'Interpreter', 'latex' );
xlabel('$i$')
ylabel('$\log(n_i) + \log(i!) - \log(N)$')
 
  
 
 [beta] = regress(poissonness, [ones(size(i)) i]) 

% beta =
%   -4.0591
%    1.4006
% 
%     Slope in the linear fit is 1.4006
%     lambda can be estimated as  exp(1.4006) = 4.0576
% 
% print -depsc 'C:\Springer\Goodness\Goodnesseps\poissonness1.eps'
% 
 figure(2)
 nk = [109 65 22 4]'; 
 k =[0 1 2 3]';
 poissonness = log(nk) + log(factorial(k)) - log(200);
 
 figure(2)
 
 plot( k, log(0.61)*k - 0.61,'r:','LineWidth',lw) 
            %theoretical line with lambda = 0.61
            hold on
 plot( k, poissonness,'o','LineWidth',lw, ...
 'MarkerEdgeColor','k', 'MarkerFaceColor','g','MarkerSize',msize);
set( get( gca, 'XLabel' ), 'Interpreter', 'latex' ); 
set( get( gca, 'YLabel' ), 'Interpreter', 'latex' );
xlabel('$i$')
ylabel('$\log(n_i) + \log(i!) - \log(N)$')  

 [beta] = regress(poissonness, [ones(size(k)) k]) 
 
% beta =
%    -0.6018
%    -0.4930
% 
% exp(-0.4930)
% ans =  0.6108
% print -depsc 'C:\Springer\Goodness\Goodnesseps\poissonness2.eps'

 
 % Hoaglin, D. (1980)   A Poissonness Plot. The American Statistician, 34, 3, 146--149.