Federico Ponzi Federico Ponzi - 4 months ago 31
Python Question

Update continuous function in real time

I can't figure how to plot a continuous function using Matplotlib. I got how to plot a scatterplot, but I would like a continuous plot.

Here is my code:

import matplotlib.pyplot as plt
from matplotlib.pyplot import autoscale
import matplotlib.animation as animation

import numpy


class MyPlot():
def __init__(self):
self.index = 0
self.setup()

def setup(self):
plt.ion()
self.fig, self.ax = plt.subplots()
self.line = self.ax.plot([],[])
autoscale()
plt.show()
def anim(self, i):
self.line.set_ydata(i) # update the data
return self.line,
def add(self, val):
print self.index, val
self.ax.plot(self.index, val)
animation.FuncAnimation(self.fig, self.anim, repeat=False)
plt.pause(0.05)
#if(self.index >= ntests):
self.index+=1

if __name__== "__main__":
import time
from random import random
p = MyPlot()

for i in range(100):
p.add(random())
time.sleep(0.5)


This works, but doesn't draw anything. The plot resizes itself, though.

Answer

You are only plotting a line with a single point at a time (which doesn't exist), so nothing shows up. If you replace self.ax.plot with self.ax.scatter, it plots correctly.

If you really want lines, you can just keep track of the last index and value and plot a line connecting the last index and value with the current index and value each time.

Add these two lines to add()

    self.ax.plot([self.index-1, self.index], [self.lastval, val])
    self.lastval = val

as well as a line initializing self.lastval to numpy.nan in setup()