0

The attached routine which I discussed recently in a related topic works well as intended. Unfortunately, when run on a fairly old computer, each while loop is taking quite some time to execute. A test to measure the duration of each loop starts with a figure of about 125ms and curiously increases slowly with each successive loop reaching to above 300ms. On a much more recent computer the numbers are better but still to high for my needs.

Can anyone suggest ways of reducing execution times? Also, why does this number increase with each iteration?

import matplotlib.pyplot as plt
import random
import time

x, y1, y2 =[],[],[]
x_scale=30
i=0

fig, (ax1, ax2) = plt.subplots(2,sharex=True)
fig.set_size_inches(8, 4)  # width and height in inches
ax1.set_title("top chart")
ax2.set_title("bottom chart")
ax2.set_xlabel("TIME")
ax1.set_ylabel("RND_1")
ax2.set_ylabel("RND_2")
    

while True:

    now =time.time()
    if len(x) > x_scale:
        x.pop(0)
        y1.pop(0)
        y2.pop(0)
    x.append(i)
    ax1.set_xlim(i-x_scale, i)
    ax2.set_xlim(i-x_scale, i)
    ax1.set_ylim(0, 150)
    ax2.set_ylim(0, 20)

    y1.append(round(100*random.random()))
    y2.append(round(10*random.random()))
    ax1.plot(x,y1, color = 'b')
    ax2.plot(x,y2, color = 'r')

    plt.draw()
#    plt.pause(0.01)
    if plt.waitforbuttonpress(0.01): break # this will wait 0.01 seconds for your keypress
    now1 = time.time()
    duration = round((now1-now)*1000)
    print(duration)
    i+=1
xuraax
  • 41
  • 2
  • each `plot` layers a new plot on top of the old one, so you have hundreds of lines. The best thing to do is `l,_ = ax.plot(x, y1)` at the first step, and then subsequent steps: `l.set_data(x, y1)`. This will change the data in the line `l`. – Jody Klymak Aug 08 '22 at 16:24
  • Does this answer your question? [How do I plot in real-time in a while loop using matplotlib?](https://stackoverflow.com/questions/11874767/how-do-i-plot-in-real-time-in-a-while-loop-using-matplotlib) – Jody Klymak Aug 08 '22 at 16:26
  • @Jody Klymak. Sorry for my late reply but I was busy away from my computer recently. I am afraid I am not sufficiently conversant with Matplotlib to understand how to implement your suggestions. I was especially confounded by your use of the underscore "_". I would be grateful if you can give more detail. Thanks in advance. – xuraax Aug 10 '22 at 13:47
  • ....oops!!! and I also missed to note the link you proposed. – xuraax Aug 10 '22 at 13:57

0 Answers0