【问题标题】:problem with generators for live updating graphs on pythonpython上实时更新图形的生成器问题
【发布时间】:2020-07-15 02:24:21
【问题描述】:

我正在尝试编写一个脚本来可视化排序算法,并且我做了我自己的快速排序版本,但我不知道如何正确使用 yield 来使我的算法工作。这是代码。

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
from itertools import chain

def update_fig(vec, rects, number):
    for rect, val in zip(rects, vec):
        rect.set_height(val)


def quick_sort(vec):
    n = len(vec)
    if n <= 1:
        return vec
    pivot = vec[n//2]
    left = []
    right = []
    for i in range(n):
        if i == n//2:
            continue
        if vec[i] >= pivot:
            right.append(vec[i])
        else:
            left.append(vec[i])

    yield chain(quick_sort(left) , [pivot] , quick_sort(right))


vec = np.random.randint(1, 100, 30)
generator = quick_sort(vec)

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
bar_rects = ax.bar(np.arange(1, len(vec) + 1), vec, align='center')

anim = animation.FuncAnimation(fig, func=update_fig, fargs=(bar_rects, 1), frames=generator, 
interval=1, repeat=False)

plt.show()

这是我得到的错误:

Traceback (most recent call last):
  File "C:\Users\Usuario\AppData\Local\Programs\Python\Python37\lib\site-packages\matplotlib\cbook\__init__.py", line 216, in process
    func(*args, **kwargs)
  File "C:\Users\Usuario\AppData\Local\Programs\Python\Python37\lib\site-packages\matplotlib\animation.py", line 953, in _start
    self._init_draw()
  File "C:\Users\Usuario\AppData\Local\Programs\Python\Python37\lib\site-packages\matplotlib\animation.py", line 1732, in _init_draw
    self._draw_frame(next(self.new_frame_seq()))
  File "C:\Users\Usuario\AppData\Local\Programs\Python\Python37\lib\site-packages\matplotlib\animation.py", line 1755, in _draw_frame
    self._drawn_artists = self._func(framedata, *self._args)
  File "C:\Users\Usuario\AppData\Local\Programs\Python\Python37\MyCodes\liveData.py", line 20, in update_fig
    rect.set_height(val)
  File "C:\Users\Usuario\AppData\Local\Programs\Python\Python37\lib\site-packages\matplotlib\patches.py", line 815, in set_height
    self._update_y1()
  File "C:\Users\Usuario\AppData\Local\Programs\Python\Python37\lib\site-packages\matplotlib\patches.py", line 745, in _update_y1
    self._y1 = self._y0 + self._height
TypeError: unsupported operand type(s) for +: 'int' and 'itertools.chain'

【问题讨论】:

    标签: python matplotlib animation graph


    【解决方案1】:

    问题确实在这里:

    yield chain(quick_sort(left) , [pivot] , quick_sort(right))
    

    您为 FuncAnimation 提供了一个整数的迭代,但您提供的动画函数具有不同的签名。请仔细阅读它们之间的相互依赖关系here。您需要提供正确的参数来驱动update_fig

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-07
      • 2017-02-28
      • 1970-01-01
      • 2020-04-06
      相关资源
      最近更新 更多