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.
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()
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With