【问题标题】:Animation using Matplotlib - Cannot run loop使用 Matplotlib 的动画 - 无法运行循环
【发布时间】:2021-08-14 18:37:22
【问题描述】:

我正在尝试使用 matplotlib 创建动画。我编写了以下代码,其中创建了一个名为update_plot() 的函数。此函数运行一个循环,其中数据更改和plot() 函数被调用。 plot() 函数清除旧图并重新绘制它。如果我尝试在 update_plot() 函数内运行一个循环(即使它不影响绘图),画布也不会显示任何内容。有谁知道为什么会这样?提前谢谢!

import math
import random
import sys
import time

import matplotlib.pyplot as plt
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas


class CanvasClickable(QWidget):

    def __init__(self, parent):
        super().__init__(parent)

        self.data = [[], []]
        self.figure = plt.figure()
        self.point_selected = None
        self.pressed = False

        self.canvas = FigureCanvas(self.figure)

        self.button = QPushButton('Plot')
        self.button.clicked.connect(self.handle_plot_button)

        layout = QVBoxLayout()
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        self.setLayout(layout)

    def plot(self):
        self.figure.clear()
        ax = self.figure.add_subplot(111)
        ax.plot(*self.data, 'o-')
        self.canvas.draw()

    def handle_plot_button(self):
        def generate_rand_points():
            return [[random.random() for i in range(5)], [10 * random.random() for i in range(5)]]

        self.data = generate_rand_points()
        self.plot()
        self.animate_plot()

    def update_plot(self, point_ind, point_coords):
        self.data[0][point_ind], self.data[1][point_ind] = point_coords[0], point_coords[1]
        self.plot()

    def animate_plot(self):

        xc = lambda t: r * math.cos(t)
        yc = lambda t: r * math.sin(t)

        r = 0.1

        t = 0.
        while True:
            print("something")
        #     xi, yi = xc(t), yc(t)
        #     self.update_plot(1, [xi, yi])
        #     t += .01
        #     time.sleep(.01)


class MainWindow(QMainWindow):

    def __init__(self):
        super().__init__()
        self.canvas = CanvasClickable(self)
        self.setCentralWidget(self.canvas)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = MainWindow()
    main.show()
    sys.exit(app.exec_())

【问题讨论】:

  • 你在使用 jupyter notebook 吗?另外,如果您将self.pause(0.1) 放在self.plot() 之后,在update_plot() 内会发生什么?
  • 不,我正在使用 PyCharm。我尝试过这个。它只是在 PyCharm IDE 中显示了一个图。

标签: python python-3.x matplotlib pyqt5


【解决方案1】:

我找到了我的答案here

据我了解,我尝试运行的循环中断了 GUI 事件循环。

所以我换了行:

self.canvas.draw() 

self.plot() 函数内部,包含以下几行:

self.canvas.draw_idle()
self.canvas.flush_events()

【讨论】:

    猜你喜欢
    • 2016-01-16
    • 1970-01-01
    • 2020-11-19
    • 2018-02-12
    • 2014-05-29
    • 2018-06-05
    • 2017-09-09
    • 2021-12-23
    • 2014-07-08
    相关资源
    最近更新 更多