How can a simple bivariate distribution be shown using ‘imshow’ in Matplotlib Python?


Matplotlib is a popular Python package that is used for data visualization. Visualizing data is a key step since it helps understand what is going on in the data without actually looking at the numbers and performing complicated computations.

It helps in communicating the quantitative insights to the audience effectively. Matplotlib is used to create 2 dimensional plots with the data. It comes with an object oriented API that helps in embedding the plots in Python applications. Matplotlib can be used with IPython shells, Jupyter notebook, Spyder IDE and so on.

It is written in Python. It is created using Numpy, which is the Numerical Python package in Python.

Python can be installed on Windows using the below command −

pip install matplotlib

The dependencies of Matplotlib are −

Python ( greater than or equal to version 3.4)
NumPy
Setuptools
Pyparsing
Libpng
Pytz
Free type
Six
Cycler
Dateutil

Bivariate distribution is the probability that a certain event would occur when two independent random variables are present.

The ‘imshow’ function is generally used to display images as well as plots in Matplotlib.

Let us understand how Matplotlib can be used to plot a bivariate distribution −

Example

import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
from matplotlib.path import Path
from matplotlib.patches import PathPatch
np.random.seed(9654241)

delta = 0.025
x = y = np.arange(−4.5, 4.5, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(−X**2 − Y**2)
Z2 = np.exp(−(X − 1)**2 − (Y − 1)**2)
Z = (Z1 − Z2) * 2

fig, ax = plt.subplots()
plt.title('A bivariate distribution')
plt.xlabel('x−axis')
plt.ylabel('y−axis')

im = ax.imshow(Z, interpolation='bilinear',
origin='lower', extent=[−3, 3, −3, 3],
vmax=abs(Z).max(), vmin=−abs(Z).max())
plt.show()

Output

Explanation

  • The required packages are imported and its alias is defined for ease of use.

  • The data is created using the ‘random’ library’s ‘seed’ function.

  • The data is created using the ‘Numpy’ library for two different data sets.

  • An empty figure is created using the ‘figure’ function.

  • The ‘subplot’ function is used to create 2 separate plots within the same plot.

  • The data is plotted using the ‘plot’ function.

  • The set_xlabel, set_ylabel and set_title functions are used to provide labels for ‘X’ axis, ‘Y’ axis and title.

  • The figure is assigned to a variable using ‘imshow’ function.

  • It is shown on the console using the ‘show’ function.

Updated on: 18-Jan-2021

376 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements