簡體   English   中英

Python \\ matplotlib:3D,動畫和散點圖

[英]Python \matplotlib: 3D, animated, and scatter plot

我幾乎是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()

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

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

在此處輸入圖片說明

對於這種形式的數據文件(這里有兩個粒子):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM