How to dynamically display time data stream on matplotlib
<p>I'm using matplotlib to display data saved on a csv file periodically,
now the data is plotted well but the time axis is hardly moving, in fact 
the script is trying to show all the data stored on that file, I want to see only latest data and be able to scrol horizontaly to see older data 
this is a part of the script : </p>

<pre><code>style.use('grayscale')

fig = plt.figure()
ax0= fig.add_subplot(511)


def animate(i):
    graph_data = open('filelocation','r').read()
    lines = graph_data.split('\n')
    xs = []
    ys = []

    for line in lines :
        if len(line)&gt;1:
            time0 , quantity0 = line.split (',')
            xs.append(dt.datetime.strptime(time0,'%H:%M:%S.%f'))
            ys.append(quantity0)

    ax0.clear()
    ax0.plot(xs,ys)


xs = matplotlib.dates.date2num(xs)
hfmt = matplotlib.dates.DateFormatter('%H:%M:%S')
ax0.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
ax0.set_ylabel('risk')
ax0.xaxis.set_major_formatter(hfmt)
ani =  animation.FuncAnimation(fig, animate, interval=1000)
plt.ticklabel_format(style='sci',axis ='y' , scilimits = (0,0))
plt.show()
plt.clear()
</code></pre>

<p>From that video, it looks like you want something like the following - I can still see a scrolling window in the video you posted so I'm still a little confused as to what you want.  This uses <code>fig.canvas.draw</code> but there are other options using the matplotlib animation module (you didn't specify that it had to be using that module).  </p>

<pre><code>import numpy as np, time
from matplotlib import pyplot as plt

import matplotlib
matplotlib.interactive(True)

rest_time = 0.001
data_stream = np.random.randn(200)

# Define the width of the viewing window (xaxis limits), 
# and the number of points to be displayed until a scrolling window starts
window_width = 40
n = 60

fig, ax = plt.subplots()
plotted_data, = ax.plot([], [], 'bo-', lw = 1.5)

x = []
y = []

ax.set_xlim([0, window_width])
ax.set_ylim([-4, 4])

for t, d in enumerate(data_stream):

    x.append(t)
    y.append(d)

    plotted_data.set_xdata(x)
    plotted_data.set_ydata(y)

    if t &gt; window_width:
        ax.set_xlim([0, t])

    if len(x) &gt; n:
        ax.set_xlim([t-n, t])

    time.sleep(rest_time)
    fig.canvas.draw()
</code></pre>

python python-2.7 python-3.x matplotlib plot