Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update matplotlib plot

I'm trying to update a matplotlib plot as follows:

import matplotlib.pyplot as plt
import matplotlib.dates as mdate
import numpy as np

plt.ion()

fig = plt.figure()
ax = fig.add_subplot(111)

for i,(_,_,idx) in enumerate(local_minima):
    dat = dst_data[idx-24:idx+25]
    dates,values = zip(*dat)
    if i == 0:
        assert(len(dates) == len(values))
        lines2d, = ax.plot_date(mdate.date2num(dates), np.array(values), linestyle='-')
    else:
        assert(len(dates) == len(values))
        lines2d.set_ydata(np.array(values))
        lines2d.set_xdata(mdate.date2num(dates))  #This line causes problems.

        fig.canvas.draw()
    raw_input()

The first time through the loop, the plot displays just fine. The second time through the loop, all of the data on my plot disappears -- everything works fine if I don't include the lines2d.set_xdata line (other than the x-data points being wrong of course). I've looked at the following posts:

How to update a plot in matplotlib?

and

Update Lines in matplotlib

However, in both cases, the user is only updating the ydata and I would like to update the xdata as well.

like image 606
mgilson Avatar asked Oct 28 '12 03:10

mgilson


1 Answers

As is the typical case, the act of writing up a question inspired me to look into a possibility I hadn't thought of previously. The x-data is being updated, but the plot ranges are not. When I put new data on the plot, it was all out of range. The solution was to add:

ax.relim()
ax.autoscale_view(True,True,True)

(partial reference)


Here's the code in context of the original question in hopes that it will be helpful to someone else someday:

import matplotlib.pyplot as plt
import matplotlib.dates as mdate
import numpy as np

plt.ion()

fig = plt.figure()
ax = fig.add_subplot(111)

for i,(_,_,idx) in enumerate(local_minima):
    dat = dst_data[idx-24:idx+25]
    dates,values = zip(*dat)
    if i == 0:
        assert(len(dates) == len(values))
        lines2d, = ax.plot_date(mdate.date2num(dates), np.array(values), linestyle='-')
    else:
        assert(len(dates) == len(values))
        lines2d.set_ydata(np.array(values))
        lines2d.set_xdata(mdate.date2num(dates))  #This line causes problems.
        ax.relim()
        ax.autoscale_view(True,True,True)
        fig.canvas.draw()
    raw_input()
like image 168
mgilson Avatar answered Sep 30 '22 17:09

mgilson