MJay
MJay

Reputation: 25

Plot a graph with incoming random data in python

I am trying to plot a graph for the data being produced using the following code.

import time
import random
import datetime

mylist = []
ct = datetime.datetime.now()

for i in range(0,61):
    x = random.randint(1,100)
    mylist.append(x)

    if len(mylist) == 11:
        right_in_left_out = mylist.pop(0)
    else:
        right_in_left_out = None
    print(mylist)

    time.sleep(1)

I want the graph to show real time plotting and at one time only 10 points should be plotted. The graph should keep moving forward just like how to data is being printed. Almost like an animation.

Upvotes: 0

Views: 513

Answers (1)

flyakite
flyakite

Reputation: 799

As Julien stated already, the linked complex example is probably what you are looking for.

Taking your code as a basis and assuming that you mixed up x- and y-coordinates, are you looking for something like this?

import time
import random
import datetime

import matplotlib.pyplot as plt

def redraw_figure():
    plt.draw()
    plt.pause(0.00001)

mylist = []
ct = datetime.datetime.now()

#initialize the data
xData = []
x = np.arange(0,10,1)
y = np.zeros(10)

#plot the data
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_ylim([0, 100])
ax.set_xlim([0, 10])
line, = ax.plot(x, y)

for i in range(0,61):
    y = random.randint(1,100)
    mylist.append(y)
    
    if len(mylist) == 11:
        right_in_left_out = mylist.pop(0)
    else:
        right_in_left_out = None
        xData.append(i)
    
    #draw the data
    line.set_ydata(mylist)
    line.set_xdata(xData)
    redraw_figure()

    print(mylist)
    time.sleep(1)

Upvotes: 1

Related Questions