Federico Ponzi Federico Ponzi - 10 months ago 63
Python Question

Matplotlib update continuos 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

def setup(self):
self.fig, self.ax = plt.subplots()
self.line = self.ax.plot([],[])
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)
#if(self.index >= ntests):

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

for i in range(100):

This works, but dosen't draw anything (but the plot resizes itself).


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()