I am trying to create an animation using matplotlib. I have written the following code, in which I have created a function called update_plot(). This functions runs a loop, in which data change and plot() function is called. The plot() function clears old plot and redraws it. If I try to run a loop inside update_plot() function (even if it doesn't affect the plot), the canvas shows nothing. Does anyone know why this happens? Thank you in advance!
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_())
self.pause(0.1)after theself.plot(), inside theupdate_plot()?