JoshJohnson
JoshJohnson

Reputation: 113

How to plot data stream in 3D

Program Description: I have a phone sending gyroscope data every 2 seconds to a server. Every second I retrieve data from the server. The purpose of my program is to read this data stream and make a 3d visualisation with matplotlib which can update automatically.

Problem: The plot displays blank 3D space although getting x,y,z coordinates. I've been trying to figure out why's and how's, but to no avail. Would really appreciate any help. Thanks in advance.

Code:

from requests import get
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np

ip_adress = 'http://xxxx'
port = ':xxxx'
endpoint = '/xxxx/'

ax = plt.axes(projection='3d')

def animate(i):
    collected_data = get(ip_adress + port + endpoint).json()['locators']['sensors'][0]
    x = np.linspace(0, collected_data['value0'], 100)
    y = np.linspace(0, collected_data['value1'], 100)
    z = np.linspace(0, collected_data['value2'], 100)
    ax.plot3D(x, y, z)
    plt.cla()

ani = FuncAnimation(plt.gcf(), animate, interval=1000)
plt.tight_layout()
plt.show()

Output:

enter image description here

Upvotes: 0

Views: 506

Answers (1)

Davide_sd
Davide_sd

Reputation: 13150

The problem is that, for each iteration you are adding a line and removing it from the plot immediately with plt.clar().

What you need to do is initialize an empty line, then in the animate function you are going to update the points:

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

ax = plt.axes(projection='3d')
line, = ax.plot3D([], [], [])

def animate(i):
    collected_data = get(ip_adress + port + endpoint).json()['locators']['sensors'][0]
    x = np.linspace(0, collected_data['value0'], 100)
    y = np.linspace(0, collected_data['value1'], 100)
    z = np.linspace(0, collected_data['value2'], 100)
    line.set_data_3d(x, y, z)

ani = FuncAnimation(plt.gcf(), animate, interval=1000)
plt.tight_layout()
plt.show()

Upvotes: 1

Related Questions