【问题标题】:Animating a Matplotlib Graph动画 Matplotlib 图
【发布时间】:2021-01-09 12:49:09
【问题描述】:

我正在尝试可视化排序算法,并且我有 updateGraph 方法可以放入新值,但是如何将值放入图表中?方法内的 plt.show() 不起作用。我读了一些关于动画方法等的东西,但我不太明白,所以非常感谢您的帮助

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

https://pastebin.com/bHX29sYJ

【问题讨论】:

标签: python sorting matplotlib bubble-sort graph-visualization


【解决方案1】:

一个选项是清除轴并为每次迭代绘制一个新的条形图。 请注意,我还添加了plt.pause(),所以显示动画。

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)

不清除情节而是更新条形图可能会更快:

h = ax.bar(range(size), randomlist)

def updateGraph(lst):
    for hh, ll in zip(h, lst):
        hh.set_height(ll)
    plt.pause(0.001) 

【讨论】:

  • 查看here 了解交互模式。使用plt.ion()激活它
  • 我还不能 :D 我需要 15 名声望,它必须得到批准
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-12
  • 2021-11-05
  • 2021-02-25
  • 2016-02-01
  • 1970-01-01
  • 2021-02-01
  • 2015-07-02
相关资源
最近更新 更多