[Matplotlib-users] continuous plotting with mplot3d

I’m using Python 2.7 on Windows 10 in a Jupyter Notebook.

I have an external orientation sensor on a USB port. I want to periodically poll that sensor at around 10Hz and update the orientation of a figure on the screen with each new sample. The sensor returns a quaternion when polled which I convert to a rotation matrix to rotate a 3D image array. This all works fine.

My problem is getting mplot3d to update the displayed image dynamically after each orientation sample. All I can get is a plot at the end of the run, nothing updates while I’m sampling. How can I change this code to plot dynamically?

Here’s my code:

*import serial.tools.list_ports # import serial module
import threespace_api_mod_Bret as ts_api
import numpy as np
import quaternion
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import time
def pack_quat_3space_array( array ):
return np.quaternion( array[3] , array[0] , array[1] , array[2] )
class SensorAnimation( object ):

def __init__(self,commport):
    # Create 3D axis
    self.fig = plt.figure()
    [self.ax](http://self.ax) = self.fig.add_subplot(111, projection='3d')
    # Initialize the 3space sensor
    self.sensor = ts_api.TSUSBSensor(commport)
    #create the 3d image to rotate
    zline = np.linspace(0, 15, 1000)
    xline = np.sin(zline)
    yline = np.cos(zline)
    # Put the 3d data into an array for rotation
    self.image_array = np.array([xline,yline,zline])
    # Draw the initial image
    self.ax.plot3D(xline, yline, zline, 'red')
    # plt.show(block=False)
def RefreshPosition( self , previous ):
    if self.sensor is not None:
        rot_matrix = quaternion.as_rotation_matrix(pack_quat_3space_array(sensor.getTaredOrientationAsQuaternion()))
        result = np.dot(rot_matrix,self.image_array)
        if previous is not None:
            try:
                plt.cla()
            except Exception as e:
                print(e)
        previous = self.ax.plot3D(result[0], result[1], result[2], 'green')
        # plt.pause(0.00001)
        return previous
def Close( self ):
    if self.sensor is not None:
        self.sensor.close()

try:
# Set up animation object
sanimate = SensorAnimation(“COM5”)
previous = None
for i in range(20):
previous = sanimate.RefreshPosition( previous )
time.sleep(0.1)
sanimate.Close()*

···

Bret Foreman
415-608-0604