简体   繁体   中英

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

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM