Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to plot data stream in 3D with matplotlib

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading