python - 在 matplotlib 中动画化 3d 散点图

标签 python matplotlib

我正在尝试在 matplotlib 中获取散点图的 3d 动画,基于发布的 2d 散点图动画 here和 3d 线图发布 here .

问题来自 set_dataset_offsets 在 3D 中不起作用,所以你应该使用 set_3d_properties 来添加 z 信息.玩弄它通常会窒息,但是下面发布的代码可以运行。然而,透明度增加到足以使点在几帧后消失。我在这里做错了什么?我希望这些点在盒子的范围内跳跃一会儿。即使将步长调整到非常小的值也不会降低透明度。

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

FLOOR = -10
CEILING = 10

class AnimatedScatter(object):
    def __init__(self, numpoints=5):
        self.numpoints = numpoints
        self.stream = self.data_stream()
        self.angle = 0

        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(111,projection = '3d')
        self.ani = animation.FuncAnimation(self.fig, self.update, interval=100, 
                                           init_func=self.setup_plot, blit=True)

    def change_angle(self):
        self.angle = (self.angle + 1)%360

    def setup_plot(self):
        x, y, z = next(self.stream)
        c = ['b', 'r', 'g', 'y', 'm']
        self.scat = self.ax.scatter(x, y, z,c=c, s=200, animated=True)

        self.ax.set_xlim3d(FLOOR, CEILING)
        self.ax.set_ylim3d(FLOOR, CEILING)
        self.ax.set_zlim3d(FLOOR, CEILING)

        return self.scat,

    def data_stream(self):
        data = np.zeros((3, self.numpoints))
        xyz = data[:3, :]
        while True:
            xyz += 2 * (np.random.random((3, self.numpoints)) - 0.5)
            yield data

    def update(self, i):
        data = next(self.stream)
        data = np.transpose(data)

        self.scat.set_offsets(data[:,:2])
        #self.scat.set_3d_properties(data)
        self.scat.set_3d_properties(data[:,2:],'z')

        self.change_angle()
        self.ax.view_init(30,self.angle)
        plt.draw()
        return self.scat,

    def show(self):
        plt.show()

if __name__ == '__main__':
    a = AnimatedScatter()
    a.show()

最佳答案

终于找到了解决方案,这里是如何更新没有触摸颜色的点:

from mpl_toolkits.mplot3d.art3d import juggle_axes
scat._offsets3d = juggle_axes(xs, ys, zs, 'z')

这是由 set_3d_properties 内部完成的以及重新初始化颜色

关于python - 在 matplotlib 中动画化 3d 散点图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11376898/

相关文章:

python - 在 matplotlib 字幕中偏移一个字符

python - 如何删除 pandas Dataframe 中的 "mirror copy"行?

python - 在 Python 中遍历嵌套字典和子字典

python - Pyplot "cannot connect to X server localhost:10.0"尽管 ioff() 和 matplotlib.use ('Agg' )

python - Matplotlib 中的颜色图,不使用 "scatter"函数

python - 极值的直方图条不可见

python - 使用 matplotlib imshow 和 scatter 获得相同的子图大小

python - 奇怪的 IPython 行为 : "pass", "return"或变量名中的 "raise"终止函数/类定义

Python-Ptrace - PtraceProcess.cont() 之后会发生什么?

python - 如何使用 Pandas 输入同一行的其他列值来返回列值?