Python: Creating a real-time 3D plot
updated: 31-01-2019
To create a real-time 3D plot from any source, where data is coming one point at a time and may have not consistent time in data retrieval.
Python along with matplotlib allows the creation of 3D plots, which is easy to create in case if data is all available at a time of plotting.
But in case of data is coming in chunks and you want to see a real-time plot of data then here is a sample code for python.
import numpy as np from mpl_toolkits.mplot3d import Axes3D from matplotlib import pyplot as plt def update_line(hl, new_data): xdata, ydata, zdata = hl._verts3d hl.set_xdata(list(np.append(xdata, new_data[0]))) hl.set_ydata(list(np.append(ydata, new_data[1]))) hl.set_3d_properties(list(np.append(zdata, new_data[2]))) plt.draw() map = plt.figure() map_ax = Axes3D(map) map_ax.autoscale(enable=True, axis='both', tight=True) # # # Setting the axes properties map_ax.set_xlim3d([0.0, 10.0]) map_ax.set_ylim3d([0.0, 10.0]) map_ax.set_zlim3d([0.0, 10.0]) hl, = map_ax.plot3D([0], [0], [0]) update_line(hl, (2,2, 1)) plt.show(block=False) plt.pause(1) update_line(hl, (5,5, 5)) plt.show(block=False) plt.pause(2) update_line(hl, (8,1, 4)) plt.show(block=True)
hl, = map_ax.plot3D([0], [0], [0]) contains initial points x=0, y=0, and z=0. You may change initial points if you want.
When you receive new data, just call:
update_line(hl, (2,2, 1)) plt.show(block=False)
This will plot new data on the graph.
plt.show(block=False) block=False, will not block the code, it will keep the code running so that it can receive new data.
But at the end of the code, you will need to call plt.show(block=True) which will block the code, so that you could analyse or save your data.
Here, we have used plt.pause(1) to create a manual delay of 1 second, which is not needed in case of real-time data processing.
Instead of (2,2,1) in update_line(hl, (2,2, 1)) , you need to replace with your new data.
You don’t need to keep previous data in the record for plotting, just add new data point and it will add that new point with all previous data points and update your graph.
Related Links:
- Python Memory Management: Quick Tips to reduce memory consumption
- Electric Potential: Visualizing Voltage with 3D animations
- Python Virtual Environment on Windows
- Python3 Packages to install before starting to code on deep learning using Tensorflow
- Errors in Simulating AVR ADC codes on Proteus
- PyFLANN for python 3x
- UDP Transceiver
- Character LCD with large/ big fonts using Arduino
- Fetching Google Search using MATLAB
- Interfacing GPS Shield for Arduino(ublox NEO-6M-0-001) with Arduino Mega 2560