Open In App
Related Articles

Insertion Sort Visualization using Matplotlib in Python

Like Article
Save Article
Report issue
Prerequisites: Insertion Sort, Using Matplotlib for Animations

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. For this we will use matplotlib, to plot bar graphs 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 a 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. The array will be stored in a matplotlib bar container object (‘rects’), where the size of each bar will be equal to the corresponding value of the element in the array.
  6. The inbuilt FuncAnimation method of matplotlib animation will pass the container and generator objects to the function used to create animation. Each frame of the animation corresponds to a single iteration of the generator.
  7. The animation function is repeatedly called will set the height of the rectangle equal to the value of the elements.


# import all the modules
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib as mp
import numpy as np
import random
# set the style of the graph'fivethirtyeight')
# input the size of the array (list here)
# and shuffle the elements to create
# a random list
n = int(input("enter array size\n"))
a = [i for i in range(1, n+1)]
# insertion sort
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 the current position
            # of elements in a
            yield a
        a[i+1] = key
        yield a
# generator object returned by the function
generator = insertionsort(a)
# to set the colors of the bars.
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)]
fig, ax = plt.subplots()
# the bar container
rects =, a, align="edge",
# setting the view limit of x and y axes
ax.set_xlim(0, len(a))
ax.set_ylim(0, int(1.1*len(a)))
# the text to be shown on the upper left
# indicating the number of iterations
# transform indicates the position with
# relevance to the axes coordinates.
text = ax.text(0.01, 0.95, "", transform=ax.transAxes)
iteration = [0]
# function to be called repeatedly to animate
def animate(A, rects, iteration):
    # setting the size of each bar equal
    # to the value of the elements
    for rect, val in zip(rects, A):
    iteration[0] += 1
    text.set_text("iterations : {}".format(iteration[0]))
anim = FuncAnimation(fig, func=animate,
                     fargs=(rects, iteration), frames=generator, interval=50,



Last Updated : 28 Jul, 2020
Like Article
Save Article
Share your thoughts in the comments
Similar Reads