Matplotlib 3D Scatter Animate Sequential Data

2019-03-05 05:47发布

问题:

I've produced the following 3D scatter plot of some accelerometer data:

It's pretty basic, but I'm pleased with the way it looks considering this is my first attempt at using Python. Here is the code that I wrote to make this visualization:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
from mpl_toolkits.mplot3d import Axes3D
from mpldatacursor import datacursor

AccX = pd.read_csv('Data_Retrieval_April_05_2017.csv')
AccX.columns = ['Tag', 'Timestamp', 'X']
AccX = AccX[AccX['Tag'].str.contains("ACC856:AccelerationX")]
del AccX['Tag']

print(AccX.head())

AccY = pd.read_csv('Data_Retrieval_April_05_2017.csv')
AccY.columns = ['Tag', 'Timestamp', 'Y']
AccY = AccY[AccY['Tag'].str.contains("ACC856:AccelerationY")]
del AccY['Tag']

print(AccY.head())

AccZ = pd.read_csv('Data_Retrieval_April_05_2017.csv')
AccZ.columns = ['Tag', 'Timestamp', 'Z']
AccZ = AccZ[AccZ['Tag'].str.contains("ACC856:AccelerationZ")]
del AccZ['Tag']

print(AccZ.head())

Accel = AccX.merge(AccY,on='Timestamp').merge(AccZ,on='Timestamp')

Accel = Accel.set_index(['Timestamp'])

print(Accel.head())

Accel['X'] = Accel.X.astype(float)
Accel['Y'] = Accel.Y.astype(float)
Accel['Z'] = Accel.Z.astype(float)

print(Accel.head())
print(Accel.dtypes)

accelscat = plt.figure().gca(projection='3d')
accelscat.scatter(Accel['X'],Accel['Y'],Accel['Z'], c='darkblue', alpha=0.5)

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

plt.show()

The data is indexed by timestamp, and looks like this:

What I'd like to do next is to take the above plot and have each point come in one at a time. Is there a simple way of doing this? Looking at the examples from matplotlib it looks like they're using randomly generated data, and then animating the lines. I'm not sure how I'd write the function that updates the figure for each row of my data.

If anyone can direct me to an example where something similar is being done, I'd really appreciate it. So far my searching has only got me examples where the data was being produced by a function or was being randomly generated.

回答1:

There is an example for 3D scatter plots in this question: Matplotlib 3D scatter animations

In order to let the points appear one by one you would plot the data from the dataframe starting at index 0 up to the current animation index i.

(df.x.values[:i], df.y.values[:i], df.z.values[:i])

A full example:

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

x = np.random.normal(size=(80,3))
df = pd.DataFrame(x, columns=["x","y","z"])


fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')
sc = ax.scatter([],[],[], c='darkblue', alpha=0.5)

def update(i):
    sc._offsets3d = (df.x.values[:i], df.y.values[:i], df.z.values[:i])

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_xlim(-3,3)
ax.set_ylim(-3,3)
ax.set_zlim(-3,3)

ani = matplotlib.animation.FuncAnimation(fig, update, frames=len(df), interval=70)

plt.tight_layout()
plt.show()