[英]How can i make points of a python plot appear over time?
I would like to create a animation where my data points would gradually appear on my graph and freeze when all the data points have appeared. 我想创建一个动画,我的数据点将逐渐显示在我的图表上,并在所有数据点出现时冻结。 I've seen in done with correlations i'm just not too sure how to do it with just individual points themselves 我已经看到完成相关性,我只是不太确定如何使用单独的点本身
This isn't something that will show anything particularly useful but i though it would look cool since i am trying to visualize some location data on a map 这不会显示任何特别有用的东西,但我会觉得很酷,因为我试图在地图上可视化一些位置数据
I know this isn't very clear so please as for clarifications, I'm not too sure how to phrase my problem very well. 我知道这不是很清楚,所以请澄清,我不太清楚如何很好地表达我的问题。
Thanks 谢谢
matplotlib.animation.FuncAnimation
is the right tool for you. matplotlib.animation.FuncAnimation
是适合您的工具。 First create an empty graph, and then gradually add data points to it in the function. 首先创建一个空图,然后在函数中逐渐添加数据点。 The following piece of code will illustrate it: 以下代码将说明它:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
x = np.arange(10)
y = np.random.random(10)
fig = plt.figure()
plt.xlim(0, 10)
plt.ylim(0, 1)
graph, = plt.plot([], [], 'o')
def animate(i):
graph.set_data(x[:i+1], y[:i+1])
return graph
ani = FuncAnimation(fig, animate, frames=10, interval=200)
plt.show()
The result (saved as gif file) is shown below: 结果(保存为gif文件)如下所示:
EDIT: To make the animation look stopped when finished in matplotlib window, you need to make it infinite (omit frames
parameter in FuncAnimation
), and set the frame counter to the last number in your frame series: 编辑:要在matplotlib窗口中完成动画看起来停止,你需要使它无限(在FuncAnimation
省略frames
参数),并将帧计数器设置为帧系列中的最后一个数字:
def animate(i):
if i > 9:
i = 9
graph.set_data(x[:i+1], y[:i+1])
return graph
ani = FuncAnimation(fig, animate, interval=200)
Or, which is better, you can set repeat
parameter in FuncAnimation
to False
, as per answer to this question. 或者,哪个更好,您可以将FuncAnimation
repeat
参数设置为False
,根据此问题的答案。
EDIT 2: To animate a scatter plot, you need a whole bunch of other methods. 编辑2:要为散点图设置动画,您需要一大堆其他方法。 A piece of code is worth a thousand words: 一段代码胜过千言万语:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
x = np.arange(10)
y = np.random.random(10)
size = np.random.randint(150, size=10)
colors = np.random.choice(["r", "g", "b"], size=10)
fig = plt.figure()
plt.xlim(0, 10)
plt.ylim(0, 1)
graph = plt.scatter([], [])
def animate(i):
graph.set_offsets(np.vstack((x[:i+1], y[:i+1])).T)
graph.set_sizes(size[:i+1])
graph.set_facecolors(colors[:i+1])
return graph
ani = FuncAnimation(fig, animate, repeat=False, interval=200)
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.