问题描述
我正在尝试如下更新matplotlib图:
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()
第一次遍历循环,该图显示得很好.第二次循环,我的绘图上的所有数据都消失了-如果我不包括 lines2d.set_xdata
行(除了x-data点当然是错误的,那一切都很好)).我看了以下帖子:
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:
和
但是,在这两种情况下,用户只更新 ydata
,我也想更新 xdata
.
However, in both cases, the user is only updating the ydata
and I would like to update the xdata
as well.
推荐答案
作为典型的案例,写一个问题的行为激发了我去寻找一种我以前没有想到的可能性.x数据 正在更新,但绘图范围未更新.当我在情节上放新数据时,一切都超出了范围.解决方案是添加:
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)
这是原始问题上下文中的代码,希望有一天能对其他人有所帮助:
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()
这篇关于更新matplotlib图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!