0

我不是初学者,但我也不是 python 代码的高级开发人员。我一直在尝试对散点图中的点移动进行动画处理,并在每个点上添加注释。我所做的只是没有注释的一点动画。我已经搜索了类似的解决方案,但它是如此令人困惑。欢迎任何帮助。这就是我所做的。

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import matplotlib.animation as animation

frame_count = 0
points = reading_file("some_data") # this method is not of intrest

def make_one_point(i):
    global frame_count, points

    ex = [1]
    ey = [1]
    ez = [1]
    point = points[i]
    frame = point[frame_count]
    ex[0] = frame[0]
    ey[0] = frame[1]
    ez[0] = frame[2]
    frame_count += 1

    return ex, ey, ez

def update(i):
    global frame_count, points

    if frame_count < len(points[i]):
        return make_one_point(i)
    else:
        frame_count = 0
        return make_one_point(i)


fig = plt.figure()
ax1 = fig.add_subplot(111, projection='3d')
ax1.set_xlim3d(-500, 2000)
ax1.set_ylim3d(-500, 2000)
ax1.set_zlim3d(0, 2000)

x = [1]
y = [1]
z = [1]
scat = ax1.scatter(x,y,z)

def animate(i):
    scat._offsets3d = update(0)

ani = animation.FuncAnimation(fig, animate, 
    frames=len(points[10]),
    interval=100, repeat=True)

plt.show()

如何同时为多个点设置动画,并在每个点上添加注释?有50分,我对效率并不那么在意,只是为了让它发挥作用。

此代码输出是移动一点动画

4

1 回答 1

2

事实证明,3D 动画文本比我预期的要难。毫不奇怪,我能够在 @ImportanceOfBeingErnest 的回答中找到问题的解决方案。然后,我简单地修改了我在之前的答案中已经编写的代码,并生成了以下代码:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D, proj3d
import matplotlib.animation as animation


N_points = 10


def update(num, my_ax):
    # the following corresponds to whatever logic must append in your code
    # to get the new coordinates of your points
    # in this case, we're going to move each point by a quantity (dx,dy,dz)
    dx, dy, dz = np.random.normal(size=(3,N_points), loc=0, scale=1) 
    debug_text.set_text("{:d}".format(num))  # for debugging
    x,y,z = graph._offsets3d
    new_x, new_y, new_z = (x+dx, y+dy, z+dz)
    graph._offsets3d = (new_x, new_y, new_z)
    for t, new_x_i, new_y_i, new_z_i in zip(annots, new_x, new_y, new_z):
        # animating Text in 3D proved to be tricky. Tip of the hat to @ImportanceOfBeingErnest
        # for this answer https://stackoverflow.com/a/51579878/1356000
        x_, y_, _ = proj3d.proj_transform(new_x_i, new_y_i, new_z_i, my_ax.get_proj())
        t.set_position((x_,y_))
    return [graph,debug_text]+annots


# create N_points initial points
x,y,z = np.random.normal(size=(3,N_points), loc=0, scale=10)

fig = plt.figure(figsize=(5, 5))
ax = fig.add_subplot(111, projection="3d")
graph = ax.scatter(x, y, z, color='orange')
debug_text = fig.text(0, 1, "TEXT", va='top')  # for debugging
annots = [ax.text2D(0,0,"POINT") for _ in range(N_points)] 

# Creating the Animation object
ani = animation.FuncAnimation(fig, update, fargs=[ax], frames=100, interval=50, blit=True)
plt.show()

在此处输入图像描述

于 2018-10-07T19:25:34.707 回答