How to handle Real-Time Matplotlib Plotting

+1 vote

hi, I have some issues with my real time plotting for matplotlib. I am using "time" on the X axis and a random number on Y axis. The random number is a static number then multiplied by a random number

import matplotlib.pyplot as plt
import datetime
import numpy as np
import time

def GetRandomInt(Data):
   timerCount=0
   x=[]
   y=[]
   while timerCount < 5000:
       NewNumber = Data * np.random.randomint(5)
       x.append(datetime.datetime.now())
       y.append(NewNumber)
       plt.plot(x,y)
       plt.show()
       time.sleep(10)

a = 10
GetRandomInt(a)

This seems to crash python as it cannot handle the updates - I can add a delay but wanted to know if the code is doing the right thing? I have cleaned the code to do the same function as my code, so the idea is we have some static data, then some data which we want to update every 5 seconds or so and then to plot the updates. Thanks!

Sep 26, 2018 in Python by bug_seeker
• 15,520 points
15,758 views

1 answer to this question.

0 votes

To draw a continuous set of random line plots, you would need to use animation in matplotlib:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()

max_x = 5
max_rand = 10

x = np.arange(0, max_x)
ax.set_ylim(0, max_rand)
line, = ax.plot(x, np.random.randint(0, max_rand, max_x))

def init():  # give a clean slate to start
    line.set_ydata([np.nan] * len(x))
    return line,

def animate(i):  # update the y values (every 1000ms)
    line.set_ydata(np.random.randint(0, max_rand, max_x))
    return line,

ani = animation.FuncAnimation(
    fig, animate, init_func=init, interval=1000, blit=True, save_count=10)

plt.show()

animated graph

The idea here is that you have a graph containing x and y values. Where xis just a range e.g. 0 to 5. You then call animation.FuncAnimation() which tells matplotlib to call your animate() function every 1000ms to let you provide new y values.

You can speed this up as much as you like by modifying the interval parameter.


One possible approach if you wanted to plot values over time, you could use a deque() to hold the y values and then use the x axis to hold seconds ago:

from collections import deque
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.ticker import FuncFormatter

def init():
    line.set_ydata([np.nan] * len(x))
    return line,

def animate(i):
    # Add next value
    data.append(np.random.randint(0, max_rand))
    line.set_ydata(data)
    plt.savefig('e:\\python temp\\fig_{:02}'.format(i))
    print(i)
    return line,

max_x = 10
max_rand = 5

data = deque(np.zeros(max_x), maxlen=max_x)  # hold the last 10 values
x = np.arange(0, max_x)

fig, ax = plt.subplots()
ax.set_ylim(0, max_rand)
ax.set_xlim(0, max_x-1)
line, = ax.plot(x, np.random.randint(0, max_rand, max_x))
ax.xaxis.set_major_formatter(FuncFormatter(lambda x, pos: '{:.0f}s'.format(max_x - x - 1)))
plt.xlabel('Seconds ago')

ani = animation.FuncAnimation(
    fig, animate, init_func=init, interval=1000, blit=True, save_count=10)

plt.show()

Giving you:

moving time plot

answered Sep 26, 2018 by Priyaj
• 58,090 points

Related Questions In Python

0 votes
1 answer

Problem in real time matplotlib plotting

Hi Sucheta, The error I can see in ...READ MORE

answered May 24, 2019 in Python by sampriti
• 1,120 points
1,143 views
0 votes
2 answers

how to print the current time using python?

print(datetime.datetime.today()) READ MORE

answered Feb 14, 2019 in Python by Shashank
• 1,370 points
686 views
0 votes
1 answer

How to get the current time in Python

>>> import datetime >>> datetime.datetime.now() datetime(2018, 25, ...READ MORE

answered Jul 25, 2018 in Python by Frankie
• 9,830 points
519 views
0 votes
1 answer

How to convert string into epoch time?

you are passing the parsed datetime object to ...READ MORE

answered Sep 22, 2018 in Python by SDeb
• 13,300 points
6,206 views
0 votes
1 answer

How to increase plt.title font size?

Try the following : import matplotlib.pyplot as plt plt.figtext(.5,.9,'Temperature', ...READ MORE

answered Feb 11, 2019 in Python by SDeb
• 13,300 points
891 views
0 votes
1 answer

pyplot tab character

I see that pylab.show actually shows some ...READ MORE

answered Mar 19, 2019 in Python by SDeb
• 13,300 points
2,562 views
0 votes
0 answers

how to remove overlapping boundaries in matplotlib?

how do i remove overlapping boundaries in ...READ MORE

Mar 26, 2019 in Python by Waseem
• 4,540 points
528 views
+1 vote
1 answer

How to create plots using python matplotlib in IPython notebook?

I think you should try: I used %matplotlib inline in ...READ MORE

answered Aug 8, 2018 in Python by Priyaj
• 58,090 points
1,211 views
0 votes
3 answers

How to get the current time in Python

FOLLOWING WAY TO FIND CURRENT TIME IN ...READ MORE

answered Apr 8, 2019 in Python by rajesh
• 1,270 points
1,697 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP