Python \ matplotlib:3D,动画和散点图

时间:2016-05-26 05:35:56

标签: python matplotlib

我几乎是Python的新手......我已经在线搜索并找到了一个2D动画python / matplotlib,它运行得很好。这是代码

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

def _update_plot(i, fig, scat):
    scat.set_offsets(([0, i],[50, i],[100, i]))
    print('Frames: %d' %i)

    return scat,

fig =  plt.figure()                

x = [0, 50, 100]
y = [0, 0, 0]

ax = fig.add_subplot(111)
ax.grid(True, linestyle = '-', color = '0.75')
ax.set_xlim([-50, 200])
ax.set_ylim([-50, 200])

scat = plt.scatter(x, y, c = x)
scat.set_alpha(0.8)

anim = animation.FuncAnimation(fig, _update_plot, fargs = (fig, scat),
                           frames = 100, interval = 100)

plt.show()

我的问题是我无法在3D中使用相同的代码,它没有显示任何内容,以下是我所做的更改:

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

def myplot(i):
    scat.set_offsets(([i,i,0],[50,i,0],[100,i,0]))
    return scat,

fig = plt.figure()

x = [0,50,100]
y = [0,0,0]
z = [0,0,0]

ax = fig.add_subplot(111, projection='3d')
ax.set_xlim([-50,200])
ax.set_ylim([-50,200])
ax.set_zlim([-50,200])

ax.set_xlabel('X ')
ax.set_ylabel('Y ')
ax.set_zlabel('Z ')

scat = plt.scatter(x,y,z, c='r', marker='o')
scat.set_alpha(0.8)

ani = animation.FuncAnimation(fig, myplot,frames = 100 , interval = 100)
plt.show()

2 个答案:

答案 0 :(得分:0)

将此scat = plt.scatter(x,y,z, c='r', marker='o')更改为

scat = ax.scatter(x,y,z, c='r', marker='o')

enter image description here

答案 1 :(得分:0)

对于此表单的数据文件(此处有两个粒子):

#     x   y   z
# t1  1   2   4
#     4   1   3
# t2  4   0   4
#     3   2   9
# t3  ...

如果t1 ... tN是时间步长/帧,您可以使用我的脚本来完成工作:

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

# Number of particles
numP = 2
# Dimensions
DIM = 3
timesteps = 2000

with open('//home//data.dat', 'r') as fp:
    particleData = []
    for line in fp:
        line = line.split()
        particleData.append(line)

x = [float(item[0]) for item in particleData]
y = [float(item[1]) for item in particleData]
z = [float(item[2]) for item in particleData]      

# Attaching 3D axis to the figure
fig = plt.figure()
ax = p3.Axes3D(fig)

# Setting the axes properties
border = 1
ax.set_xlim3d([-border, border])
ax.set_ylim3d([-border, border])
ax.set_zlim3d([-border, border])


def animate(i):
    global x, y, z, numP
    #ax.clear()
    ax.set_xlim3d([-border, border])
    ax.set_ylim3d([-border, border])
    ax.set_zlim3d([-border, border])
    idx0 = i*numP
    idx1 = numP*(i+1)
    ax.scatter(x[idx0:idx1],y[idx0:idx1],z[idx0:idx1])

ani = animation.FuncAnimation(fig, animate, frames=timesteps, interval=1, blit=False, repeat=False)
plt.show()