我想使用matplotlib动画实时绘制两个列表,在社区的帮助下,我能够绘制我的图形。我现在想要简化我的实时动画并重新构建我的图形。
以下是我的目标:
到目前为止,我不知道我的代码出了什么问题:
class StdOutListener(StreamListener):
def on_data(self, data):
json_load = json.loads(data)
texts = json_load['text'] # string
#print(texts)
#drop zero in list
if 0 in my_list: my_list.remove(0)
#print
#calculate average
average = numpy.mean(my_list)
b = my_average.append(average)
print "average =", my_average
def __init__(self):
self.start_time = time.time()
self.x = [len(my_average)]
self.y = [my_average]
self.my_average = []
self.line_actual, = plot(self.x, self.y) # line stores a Line2D we can update
self.line_average, = plot(self.x, self.my_average) # line stores a Line2D we can update
def on_data(self, new_value):
time_delta = time.time() - self.start_time # on our x axis we store time since start
self.x.append(time_delta)
self.y.append(new_value)
self.my_average.append(numpy.mean(self.y))
self.line_actual.set_data(self.x, self.y)
self.line_average.set_data(self.x, self.my_average)
ylim([min(self.y), max(self.y)]) # update axes to fit the data
xlim([0, max(self.x)])
draw() # redraw the plot
ion() # ion() allows matplotlib to update animations.
out_listener = StdOutListener()
for i in range(10000):
out_listener.on_data(i + numpy.random.randint(-5,5))
先谢谢你
答案 0 :(得分:1)
所以:
我不确定列表的绘图长度是什么意思。但我假设您要创建索引从0到len(my_average)
的索引数组。这就是range
的用途:
self.x = range(len(my_average))
您已经使用了ylim
功能,它可以完全满足您的需求。但是,您只需传递所需的静态值,而不是传递数据的最小值/最大值:
ylim(-1, 1)