Search code examples
pythonsortingmatplotlibbubble-sortgraph-visualization

Animating a Matplotlib Graph


Im trying to visualize a sorting algorithm and I have the updateGraph method to put in the new values, but how do I put the values in the Graph? plt.show() inside the method doesnt work. I read some stuff about animation methods and such but I didnt really understand so help would be really appreciated

def updateGraph(list): plt.bar(range(0, int(size)), list) plt.show()

https://pastebin.com/bHX29sYJ


Solution

  • One option is to clear the axis and draw a new bar plot for every iteration. Note that I also added plt.pause() so show the animation.

    from matplotlib import pyplot as plt
    import random
    
    size = 10
    
    fig, ax = plt.subplots()
    plt.title("Bubble Sort Visualization")
    plt.xlim((-0.6, size-0.4))
    plt.ylim((0, size))
    
    def updateGraph(lst):
        plt.cla()
        plt.bar(range(0, int(size)), lst)
        plt.pause(0.2)  # Choose smaller time to make it faster 
        plt.show()
    
    def bubbleSort(lst):
        n = len(lst)
        elementsInPlace = 0
        comparisonCount = 0
    
        while n > 1:
            for i in range(len(lst) - elementsInPlace - 1):
                if lst[i] > lst[i + 1]:
                    comparisonCount += 1
                    lst[i], lst[i + 1] = lst[i + 1], lst[i]
                    updateGraph(lst)
                else:
                    comparisonCount += 1
    
            n -= 1
            elementsInPlace += 1
        return lst
    
    randomlist = random.sample(range(1, int(size) + 1), int(size))
    bubbleSort(randomlist)
    

    It might be faster to not clear the plot but rather update the bars:

    h = ax.bar(range(size), randomlist)
    
    def updateGraph(lst):
        for hh, ll in zip(h, lst):
            hh.set_height(ll)
        plt.pause(0.001)