Oct-07-2021, 05:12 AM
I have a requirement to do animation with matplotlib and also generate/manipulate the data to be plotted. I was hoping to get this done in the same program using threading - one thread to generate/manipulate the data and write to a text file AND another thread to read this data and do the plotting/animation. I wrote a test script to try this out as below. I have a function incremnt() in which I intend to do the data generation/manipulation. For testing I am just doing a sleep and print statements. I also have a function loop_animate() which calls FuncAnimation with animate() as the animation function. I am using threading to create two threads t1 and t2 and calls incremnt and loop_animate in each of these threads. But when I run it, it just hangs. If I comment the animate and loop_animate functions, uncomment test_func and call this function in thread t2 instead of calling loop_animate, the threading works file and prints the messages from incremnt and test_func as expected. I could probably do this as two separate python scripts but trying to avoid that. Can someone help to sort this out?
import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation from itertools import count import time import random import threading xcord = [] ycord = [5,3] index = count() xcord.append(next(index)) xcord.append(next(index)) fig, ax = plt.subplots(1,1) xmin, xmax = (0,29) print(' xmin is {xmin}'.format(xmin=xmin)) print(' xmax is {xmax}'.format(xmax=xmax)) def animate(i,*args): global xmin, xmax, xcord, ycord xcord.append(next(index)) ycord.append(random.randint(3,8)) print(xcord) print(ycord) plt.cla() xmin = xmin + 1 if xcord[len(xcord)-1] > 28 else 0 xmax = xmax + 1 if xcord[len(xcord)-1] > 28 else 29 args[0].set(xlim=(xmin,xmax), ylim=(0, 10)) args[0].plot(xcord,ycord) def loop_animate(): global fig, ax print('Inside loop_animate') ani = FuncAnimation(fig, animate,interval=500) plt.tight_layout() plt.show() ''' def test_func(): cnt = 0 while cnt < 5: print('Sleeping inside test_func') time.sleep(3) cnt += 1 print('Done sleeping inside test_func') ''' def incremnt(): cnt = 0 while cnt < 5: print('Sleeping inside fn incremnt') time.sleep(3) cnt += 1 print('Done sleeping inside incremnt') t1 = threading.Thread(target = incremnt) t2 = threading.Thread(target = loop_animate) t1.start() t2.start() print('Threads started') t1.join() t2.join() print('All done')