在matplotlib中向3d散点图迭代添加点

时间:2019-02-20 09:07:59

标签: python matplotlib scatter-plot scatter3d

我当前的代码未产生预期的结果:

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
colors = cm.rainbow(np.linspace(0, 1, len(gt_x)))
for i in range(len(gt_x)):
    ax.scatter(gt_x[i], gt_y[i], gt_z[i], s=50, marker='o', c=colors[i], label='gt')
    ax.scatter(pred_x[i], pred_y[i], pred_z[i], s=50, marker='x', c=colors[i], label='predicted')
    fig.canvas.draw()
    data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="")
    data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
    imgs.append([plt.imshow(data, animated=True)])

clip = animation.ArtistAnimation(fig, imgs, interval=100, blit=False, repeat_delay=1000)
name = os.path.join("../data", "scatter_plot") + ".gif"
clip.save(name, writer='imagemagick')

我想使用相同的逻辑,即用FuncAnimation和偏移量将3d点迭代地添加到散点图中,这似乎是我想要做的正确方法。

但是,这涉及使用3D偏移量和斧头更新功能,我不知道如何将其用于此目的,因为许多功能似乎是私有的,因此未记录在案,例如ax._3doffsets()

1 个答案:

答案 0 :(得分:0)

在我的示例中,使用私有matplotlib函数以迭代方式将点添加到具有不同标记和颜色的动画3D散点图中的解决方案如下:

import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.markers as mmarkers
import matplotlib.cm as cm
import matplotlib.animation

colors = cm.tab10(np.linspace(0, 1, len(pos_gt)))


def update_graph(num):
    x_updated = np.concatenate([pos_gt.x[:num+1].tolist(), pos_pred.x[:num+1].tolist()])
    y_updated = np.concatenate([pos_gt.y[:num+1].tolist(), pos_pred.y[:num+1].tolist()])
    z_updated = np.concatenate([pos_gt.z[:num+1].tolist(), pos_pred.z[:num+1].tolist()])

    paths_gt = []
    paths_ped = []
    for i in range(num+1):
        marker_gt = mmarkers.MarkerStyle('o')
        marker_ped = mmarkers.MarkerStyle('x')
        path_gt = marker_gt.get_path().transformed(marker_gt.get_transform())
        path_ped = marker_ped.get_path().transformed(marker_ped.get_transform())
        paths_gt.append(path_gt)
        paths_ped.append(path_ped)

    graph._paths = np.concatenate([paths_gt, paths_ped])
    graph._facecolor3d = np.concatenate([colors[:num+1],colors[:num+1]])
    graph._edgecolor3d = np.concatenate([colors[:num+1],colors[:num+1]])
    graph._offsets3d = (x_updated, y_updated, z_updated)



fig = plt.figure(dpi=200)
ax = fig.add_subplot(111, projection='3d')
title = ax.set_title('plot title')


graph = ax.scatter([], [], [], s=70)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_zlim(0, 1)
graph.set_alpha(1)

ani = matplotlib.animation.FuncAnimation(fig, update_graph, frames=9, interval=600, repeat_delay=5000, blit=False)

plt.show()