使用 matplotlib 实时更新 [英] live updating with matplotlib
问题描述
所以我有一些手机加速度测量数据,我想基本上制作一个关于手机运动的视频.所以我使用 matplotlib 创建了数据的 3D 图:
So I have some phone accelerometry data and I would like to basically make a video of what the motion of the phone looked like. So I used matplotlib to create a 3D graph of the data:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import pandas as pd
import pickle
def pickleLoad(pickleFile):
pkl_file = open(pickleFile, 'rb')
data = pickle.load(pkl_file)
pkl_file.close()
return data
data = pickleLoad('/Users/ryansaxe/Desktop/kaggle_parkinsons/accelerometry/LILY_dataframe')
data = data.reset_index(drop=True)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
xs = data['x.mean']
ys = data['y.mean']
zs = data['z.mean']
ax.scatter(xs, ys, zs)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
现在时间很重要,实际上也是我一次只能看到一个点的一个因素,因为时间也是一个因素,它让我可以观察加速度数据的进展!
Now time is important and is actually also a factor that I only see one point at a time because time is also a factor and it lets me watch the progression of the accelerometry data!
我可以用它做什么来使其成为实时更新图表?
What can I do with this to make it a live updating graph?
我唯一能想到的就是有一个循环,逐行遍历并从行中生成图形,但这会打开太多文件,这会很疯狂,因为我有数百万行.
Only thing I can think of is to have a loop that goes through row by row and makes the graph from the row, but that will open so many files that it would be insane because I have millions of rows.
那么如何创建实时更新图表?
So how can I create a live updating graph?
推荐答案
这是一个尽可能快地更新的基本示例:
Here is a bare-bones example that updates as fast as it can:
import pylab as plt
import numpy as np
X = np.linspace(0,2,1000)
Y = X**2 + np.random.random(X.shape)
plt.ion()
graph = plt.plot(X,Y)[0]
while True:
Y = X**2 + np.random.random(X.shape)
graph.set_ydata(Y)
plt.draw()
诀窍是不是继续创建新图形,因为这会继续占用内存,而是更改现有绘图上的 x、y、z 数据.使用 .ion()
和 .draw()
设置画布以进行更新.
The trick is not to keep creating new graphs as this will continue to eat up memory, but to change the x,y,z-data on an existing plot. Use .ion()
and .draw()
setup the canvas for updating like this.
附录:@Kelsey 在下面的评论中指出:
Addendum: A highly ranked comment below by @Kelsey notes that:
您可能需要在 plt.draw()
行之后使用 plt.pause(0.01)
来刷新显示
You may need a
plt.pause(0.01)
after theplt.draw()
line to get the refresh to show
这篇关于使用 matplotlib 实时更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!