gpt4 book ai didi

python - 我怎样才能使 python 图的点随着时间的推移出现?

转载 作者:行者123 更新时间:2023-11-28 20:05:04 25 4
gpt4 key购买 nike

我想创建一个动画,让我的数据点逐渐出现在我的图表上,并在所有数据点出现后卡住。我已经看到完成相关性我只是不太确定如何只用个别点自己来做

这不会显示任何特别有用的东西,但我认为它看起来很酷,因为我正在尝试在 map 上可视化一些位置数据

我知道这不是很清楚,所以请澄清一下,我不太确定如何很好地表达我的问题。

谢谢

最佳答案

matplotlib.animation.FuncAnimation是适合您的工具。首先创建一个空图,然后在函数中逐渐向其中添加数据点。下面的一段代码将对此进行说明:

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

结果(保存为gif文件)如下图: enter image description here

编辑:要使动画在 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)

或者,根据对 this 的回答,您可以将 FuncAnimation 中的 repeat 参数设置为 False,哪个更好?问题。

编辑 2: 要制作散点图的动画,您需要一大堆其他方法。一段代码胜过一千字:

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

关于python - 我怎样才能使 python 图的点随着时间的推移出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33275189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com