Realtime Subplots Updating

Viewed 34

The following code works well for me to display and update in real time on one chart data coming from 2 sources:

import matplotlib.pyplot as plt
import random
import time
fig = plt.gcf()
fig.set_size_inches(12, 6)  # width and height in inches
fig.show()

i=1
x, y1, y2 = [], [],[]
x_scale = 30
plt.ylabel('random')
plt.xlabel('Sample')
plt.ylim(top = 100, bottom = 0)

while True:
    if len(x) > x_scale:
        x.pop(0)
        y1.pop(0)
        y2.pop(0)
    x.append(i)
    y1.append(round(100*random.random()))
    y2.append(round(10*random.random()))
    plt.plot(x,y1, color = 'b')
    plt.plot(x,y2, color = 'r')
    plt.xlim(left=i-x_scale, right=i)
    fig.canvas.draw()
    if plt.waitforbuttonpress(0.1): break # this will wait 0.1 seconds for your keypress
    i += 1

I need to do something similar, this time plotting separate data on separate charts. The following code based on the above is not working:

import matplotlib.pyplot as plt
import random

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

fig, (ax1, ax2) = plt.subplots(2,sharex=True)
ax1.set_title("top chart")
ax2.set_title("bottom chart")
    
plt.show()


while i<40:
    if len(x) > x_scale:
        x.pop(0)
        y1.pop(0)
        y2.pop(0)
    x.append(i)
    plt.xlim(left=i-x_scale, right=i)

    y1.append(round(100*random.random()))
    y2.append(round(10*random.random()))
    ax1.plot(x,y1)
    ax2.plot(x,y2)

    plt.draw()
    i+=2

Any suggestions please.

1 Answers

Following DavidG's suggestion and some further experimentation here follows the code which in the end worked for me:

import matplotlib.pyplot as plt
import random

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

fig, (ax1, ax2) = plt.subplots(2,sharex=True)
fig.set_size_inches(15, 8)  # 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:

    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.1 seconds for your keypress

    i+=1

Instead of the plt.pause() I used the plt.waitforbuttonpress() which accomplished the same job but also enabled me to use an infinite loop for continuous plotting yet allows me to exit neatly by pressing esc when I want to. The anomalous issue with the x axis I reported was resolved by removing a command which I had inserted earlier whilst searching for a solution. I hope someone may find this useful. cheers

Related