Skip to content
Related Articles

Related Articles

Improve Article

3D Visualisation of Insertion Sort using Matplotlib in Python

  • Last Updated : 28 Jul, 2020

Prerequisites: Insertion Sort, Introduction to Matplotlib

Visualizing algorithms makes it easier to understand them by analyzing and comparing the number of operations that took place to compare and swap the elements. 3D visualization of algorithms is less common, for this we will use matplotlib to plot bar graphs and animate them to represent the elements of the array.


  1. We will generate an array with random elements.
  2. The algorithm will be called on that array and yield statement will be used instead of return statement for visualization purposes.
  3. We will yield the current states of the array after comparing and swapping. Hence the algorithm will return a generator object.
  4. Matplotlib animation will be used to visualize the comparing and swapping of the array.
  5. We will then plot the graph, which will return an object of Poly3dCollection using which further animation will be done.

Below is the implementation.


# import the modules
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from mpl_toolkits.mplot3d import axes3d
import matplotlib as mp
import numpy as np
import random
# Array size
n = 11
# insertion sort algorithm
def insertionsort(a):
    for j in range(1, len(a)):
        key = a[j]
        i = j-1
        while(i >= 0 and a[i] > key):
            a[i+1] = a[i]
            i -= 1
            yield a
        a[i+1] = key
        yield a
# method to plot graph
def showGraph(n):
    # for random unique values
    a = [i for i in range(1, n+1)]
    datasetName = 'Random'
    algoName = 'Insertion Sort'
    # generator object returned by the function
    generator = insertionsort(a)
    # the style of the graph'fivethirtyeight')
    # set bar colors
    data_normalizer = mp.colors.Normalize()
    color_map = mp.colors.LinearSegmentedColormap(
            "red": [(0, 1.0, 1.0),
                    (1.0, .5, .5)],
            "green": [(0, 0.5, 0.5),
                      (1.0, 0, 0)],
            "blue": [(0, 0.50, 0.5),
                     (1.0, 0, 0)]
    # plot the array
    fig = plt.figure()
    ax = fig.add_subplot(projection='3d')
    # the z values and position of the bars
    z = np.zeros(n)
    dx = np.ones(n)
    dy = np.ones(n)
    dz = [i for i in range(len(a))]
    # plot 3d bars
    rects = ax.bar3d(range(len(a)), a, z, dx, dy, dz,
    ax.set_xlim(0, len(a))
    ax.set_ylim(0, int(1.1*len(a)))
    ax.set_title("ALGORITHM : "+algoName+"\n"+"DATA SET : "+datasetName,
                 fontdict={'fontsize': 13
                           'fontweight': 'medium'
                           'color': '#E4365D'})
    # 2D text placed on the upper left 
    # based on the axes fraction
    text = ax.text2D(0.1, 0.95, "", 
    iteration = [0]
    # function for animating
    def animate(A, rects, iteration):
        # to clear the bars from the 
        # Poly3DCollection object
        ax.bar3d(range(len(a)), A, z, dx, dy, dz,
        iteration[0] += 1
        text.set_text("iterations : {}".format(iteration[0]))
    anim = FuncAnimation(fig, func=animate,
                         fargs=(rects, iteration),
                         frames=generator, interval=50,
# Driver Code

Output :

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :