Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...