Plot real-time terminal data

A python script to plot 1D real-time data being written to the stdout by other application

When we develop software to process data, there is often a need to quickly visualize it for debug purposes. One most common option is to write the data to the stdout of the terminal. For example:

• print data in Python
• std::cout << data << std::endl; in C++

However, sometimes plotting the data makes more sense. In this article, I’ll show an example of how to develop a simple tool to plot such data in real-time.

Python script to plot multiple sets of 1D data

The script should be able to 1) read data from the terminal and 2) plot the data. One way to read from the terminal is to use pipe to redirect the data from the application writing the data to this script.
For example: $python some_application.py | python plot_script.py Once the data is being redirected, we can read it in python by the following script (plot_script.py): You may try running it as: $ ping 127.0.0.1 | python plot_script.py

‘data’ variable in the above script has to be plotted now. In this article, I’ll show you how to parse multiple streams of 1D data. We first generate such synthetic data for the sake of demonstration (synthetic-data.py):

with comma separated output. Here I demonstrate 3 sets of 1D data (x,y,z) also represented as variables.

> 0.0,1.0,-0.0
> 0.0174435597087,0.999847849537,-0.0174435597087
> 0.0348818113261,0.999391444449,-0.0348818113261
> 0.052309448376,0.99863092362,-0.052309448376
> 0.0697211676123,0.997566518477,-0.0697211676123
> 0.0871116706329,0.99619855292,-0.0871116706329
> 0.104475665491,0.994527443221,-0.104475665491
> 0.121807868308,0.992553697902,-0.121807868308
.
.


Thus, we can parse the ‘data’ in ‘plot_script.py’ using data.split(','). After adding the matplotlib functions, here is our final ‘plot_script.py’ script.

This script accepts two arguments:

• -t: The length of X axis. Since the input data is a time-series data, each input is considered a timestep. Thus this variable determines the number of past timesteps to plot from the current time.
• -n: Number of variables to plot in the input data. The respective values for the different variables in a timestep are presented in a comma-separated string. Thus, this script can plot multiple 1D data variables.

To visualize the synthetic data we generated before.
Run \$ python synthetic-data.py | python plot_script.py -t 1000 -n 3

Here is the graph output with different color for different variables: