如何使python图的点随时间而出现?

2024-05-06 16:04:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个动画,其中我的数据点将逐渐出现在我的图表和冻结时,所有的数据点已经出现。我在《与相关性的了结》一书中看到,我只是不太确定如何仅用个人观点来做

这不是什么特别有用的东西,但我觉得它看起来很酷,因为我正试图在地图上可视化一些位置数据

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

谢谢


Tags: 数据可视化图表地图动画正试图点将个人观点
1条回答
网友
1楼 · 发布于 2024-05-06 16:04:17

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

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

相关问题 更多 >