Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dynamically update my matplotlib figure as the data file changes?

I have a python script that reads in a data file and displays one figure with four plots using the matplotlib library. The data file is being updated every few seconds since it is an output file for a different piece of software that is running concurrently. I would like the four plots in my matplotlib figure to refresh themselves using the updated data file every 20 seconds. The way I've implemented this is as follows:

import pylab as pl
import time

pl.ion()
fig = pl.figure()
while True:
    f = open('data.out', 'rb')
    #code to parse data and plot four charts
    ax = fig.add_subplot(2,2,1)
    #...
    ax = fig.add_subplot(2,2,4)
    #...
    pl.draw()
    time.sleep(20)

This works, but I lose functionality of the zoom and pan buttons which normally work if pl.show() is called. This is not optimal. However, if pl.show() is substituted for pl.draw(), the script no longer updates the plots. Is there a way to dynamically update a plot without completely losing the zoom/pan functionality?

like image 374
S Kulk Avatar asked Dec 06 '11 20:12

S Kulk


1 Answers

Your code is a little too vague to know what is going on.

I can offer this: You should retain normal functionality if you create your subplots once, saving all the axes objects and then calling show().

Subsequent changes to those subplots could be done like this:

#inside while loop
for i in #subplotlist
    ax[i].clear()    #ax[i] is the axis object of the i'th subplot
    ax[i].plot(#plotstuff)
    ax[i].draw()

The toolbar for zooming and panning can be added by hand if you so desire.

like image 77
Dani Gehtdichnixan Avatar answered Oct 24 '22 13:10

Dani Gehtdichnixan