Home

3D Drawing of a Bivariate Normal Distribution

A Python script

 

The bivariate normal distribution, each variate of which has variance 1, is represented by this:

where  is the correlation coefficient.

Figure 1 shows a graph of equation (1) with .

Figure 1

 

The script, which drew the graph in Figure 1, is this.

 



from mpl_toolkits.mplot3d import Axes3D

import matplotlib.pyplot as plt

import numpy as np

import math

 

class BiVarNorm:

    """

            Bivariate normal distribution

    """

    def __init__(self, rho):

        self.rho = rho

 

    def value(self, x, y):

        v = (x**2 + y**2 - 2 * self.rho * x * y) / (2.0 * (1.0 - self.rho**2))

        v = np.exp(-v) / ((2.0 * math.pi * (1.0 - self.rho**2)) ** 0.5)

        return v

   

while True:

    rho = float(input('rho = '))

    if math.fabs(rho) >= 1.0:

        break

    fig = plt.figure()

    ax = Axes3D(fig)

    Xg = np.arange(-4.0, 4.0, 0.1)

    Yg = np.arange(-4.0, 4.0, 0.1)

    X, Y = np.meshgrid(Xg, Yg)

    bi_norm = BiVarNorm(rho)

 

    ax.plot_surface(X, Y, bi_norm.value(X, Y), rstride = 1, cstride = 1, cmap = plt.cm.coolwarm)

 

    plt.show()

 

print('\nGoodbye !\n')



 

The function gvalueh of the above script, which is also shown below, calls the function np.exp.

    def value(self, x, y):

        v = (x**2 + y**2 - 2 * self.rho * x * y) / (2.0 * (1.0 - self.rho**2))

        v = np.exp(-v) / ((2.0 * math.pi * (1.0 - self.rho**2)) ** 0.5)

        return v

When np.exp is replaced by math.exp, a TypeError will be displayed. A script, in which a function is not called with a list argument, is discussed in this website.

 

Run the above script, then the input for rho is required (Figure 2).

Figure 2

 

Set a value, whose absolute value is less than 1, then the graph of the bivariate normal distribution with the correlation coefficient of the value specified is displayed (Figure 1). You can rotate the image by dragging it by the mouse (Figure 3).

Figure 3

 

When the form is closed by clicking the icon X at the upper right corner, the next value for rho is asked (Figure 4).

Figure 4

 

If the absolute value of rho is less than 1, the corresponding graph will be displayed. But, if the absolute value is larger than or equal to 1, the script exits.

 

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

 

 

Home