Home

Drawing a Joint Distribution of a Binomial Distribution

A Python script

 

The basic model in Bayesian statistics is given by the following equation (Gelman, Carlin, Stern, Dunson, Vehtari, and Rubin (2014). Bayesian Data Analysis, third edition. CRC Press).

From model (1), we have the conditional distribution of parameter  given data D.

 

Now, consider a binomial distribution given by this

where data D and parameter  are denoted by the frequency X and the probability p, respectively.

Set the prior distribution as a uniform one. That is,

From (1), we have

A 3-D graphic image of the above joint distribution is shown in Figure 1.

Figure 1

 

The image in Figure 1 can be rotated by dragging on it by the mouse (Figure 2).

Figure 2

 

The red line in Figure 2 indicates the intercept, which corresponds to the posterior distribution .

 

The Python script, which produced the graph in Figure 1 is as follows.

 

==========================================

from mpl_toolkits.mplot3d import Axes3D

import matplotlib.pyplot as plt

import numpy as np

import math

 

def combi(N, k):

    v = 1

    if (0 < k) and (k < N):

        for i in range(1, k+1):

            v *= (N - i +1) / i

    return v

 

 

fig = plt.figure()

ax = Axes3D(fig)

X = np.arange(0, 10.1, 1)

P = np.arange(0.0, 1.001, 0.01)

Xg, Pg = np.meshgrid(X, P)

 

def f(x, p):

    return  combi(10, x) * (p**x) * ((1-p)**(10-x))

 

Z = []

pos = -1

for p in P:

    Z.append([])

    pos += 1

    for x in X:

        Z[pos].append(f(int(x), p))

Z = np.array(Z)

 

ax.plot_surface(Xg, Pg, Z, rstride = 1, cstride = 1, cmap = plt.cm.coolwarm)

 

plt.show()

===========================================

 

The points of grids of X and p are stored in the following lists:

 

X =

[X1,  X2, ・・・, Xm]

P =

[P1, P2, ・・・, Pn]

 

The corresponding values of the function are set as the following list:

 

Z =

[

[f(X1, P1),

f(X2, P1),

・・・

f(Xm, P1)],

[f(X1, P2),

f(X2, P2),

・・・

f(Xm, P2)],

[f(X1, Pn),

f(X2, Pn),

・・・

f(Xm, Pn)]

]

 

The script file is archived in the file Prg.zip, which can be downloaded by clicking the file name Prg.zip.

 

In the above script, the third argument Z of the function plot_surface is constructed by explicitly calculating each item value in the list. But, if the function accepts a list as an argument, we need not calculate the values by calling the function for each item. For a sample script using a function, which accepts a list, visit this website.

 

 

Home