Help Streaming Unknown number of Traces

Hello,

I have a large amount of data where I would like to be able to have a user select which variables they wish to plot. The number of traces will vary based on the number of selections. I am having trouble getting this to work correctly. I am trying to save the selection data into arrays, but I cannot get it to work.

The function below gets called repeatedly from another function. “data” is an array that contains the new values that I would like to plot starting at index 2. I would like to stream each new value as a separate trace. The first time it executes it builds the plot correctly. I am having trouble with the second half after the else. I need x and y to be an array of all the values with x being time and y being the variable value.
Any idea what is wrong?
Thank you

function plotlylive(data){		

var timearray= [];
var time = new Date();
var numplots = [];
var xdata=[];
var ydata = [];
var plotdata = [];

if (liveloaded == false){

		var update = [];
	    for ( var j = 2; j < data.length; j++ ) {
		
		 	var plotdata = {
			  x: [time],
			  y: [data[j]],
			  mode: 'lines'
			}
			update.push(plotdata);
			numplots.push(j-2);
		 }
     
	console.info(update);
	Plotly.plot('plotlydivLive', update);
	liveloaded = true;
	
}else{

	var newtime = [];
	var newdata = [];
	
	//this didnt work
/*      for ( var j = 2; j < data.length; j++ ) {
			numplots.push(j-2);
			newtime.push(time);
			newdata.push(data[j]);
			}

	var update = {
	  x: [[newtime]],
	  y: [[newdata]],
	  mode: 'lines'
	}	 */ 
	
	//this didnt work
/* 	var update = [];
    for ( var j = 2; j < data.length; j++ ) {
		 	var plotdata = {
			  x: [time],
			  y: [data[j]]
			}
			update.push(plotdata);
			numplots.push(j-2);
			}

	console.info(update);
 */
		//this works buts its fixed to 2 values
		/*   var update = {
			x: [[time], [time]],
			y: [[data[2]], [data[3]]]
			
		  }   */
		  var xval = []
		  var yval = [];
      for ( var j = 2; j < data.length; j++ ) {
			numplots.push(j-2);
			xval.push(time);
			yval.push(data[j]);
			}


		  var olderTime = time.setMinutes(time.getMinutes() - 1);
		  var futureTime = time.setMinutes(time.getMinutes() + 1);

		  var minuteView = {
				xaxis: {
				  type: 'date',
				  range: [olderTime,futureTime]
				}
			  };
	var xtext = ['[' + time + '],[' + time +']'];
	Plotly.relayout('plotlydivLive', minuteView);
	Plotly.extendTraces('plotlydivLive', { x: [xtext], y: [[yval]]},numplots);
	//Plotly.extendTraces('plotlydivLive', { x: [[time],[time]], y: [[data[2]],[data[3]]]},[0,1]);
										   //{ x: [[time],[time]], y: [[80]        , [55]]}       ,[0,1]"
											//{x: [[time], [time]],y: [[80], [55]]}
	
	//Plotly.extendTraces('plotlydivLive', update);		
  }

}

Did you find the solution? I am in an exactly similar situation. A reply will be greatly appreciated.

With regards,

Raghav

Here is the code that I am using now that is working for me.

function plotlylive(data){

var timearray= ;
var time = new Date();
var numplots = ;
var xdata=;
var ydata = ;
var plotdata = ;

if (liveloaded == false){

	var update = [];
    for ( var j = 2; j < data.length; j++ ) {
	
	 	var plotdata = {
		  x: [time],
		  y: [data[j]],
		  type: 'scattergl',
		  mode: 'lines',
		  name: labelslive[j] ,
		}
		update.push(plotdata);
		numplots.push(j-2);
	 }
 
//console.info(update);

var layout = {

title: ‘Live Streaming Data’,
hoverlabel:{namelength: -1}
};

Plotly.newPlot('plotlydivLive', update,layout,{responsive: true, scrollZoom: true});
liveloaded = true;

}else{

var newtime = [];
var newdata = [];

	//this works 
	   var update = {
		x: [[time], [time]],
		y: [[data[2]], [data[3]]]		
	  }   
	//console.info(update);
	var xvals = [];
	var yvals = [];
	var numplots = [];
	
    for ( var j = 2; j < data.length; j++ ) {
		xvals.push([time]),
		yvals.push([data[j]]),
		 numplots.push(j-2);
	 }

	   var update = {
		x: xvals,
		y: yvals,		
	  }  

	//console.info(update);
	
	  var olderTime = time.setMinutes(time.getMinutes() - 1);
	  var futureTime = time.setMinutes(time.getMinutes() + 1);

	  var minuteView = {
			xaxis: {
			  type: 'date',
			  range: [olderTime,futureTime]
			}
		  };

//Plotly.relayout('plotlydivLive', minuteView);
Plotly.extendTraces('plotlydivLive', update,numplots);		

}

}

I tried your code to no avail. I will share my original peace of code perhaps you can figure out what is wrong, this piece of code produces only one Trace, adding more traces results in a strange phenomenon with many colours!

                setInterval(() => {
                    if (this.__bLiveData == true) {

                        //@ts-ignore
                        this.__plotlyLayout.xaxis.autorange = true;
                        //@ts-ignore
                        this.__plotlyLayout.yaxis.autorange = true;
                        //@ts-ignore
                        this.__plotlyLayout.yaxis2.autorange = true;
                        //@ts-ignore
                        this.__plotlyLayout.yaxis3.autorange = true;
                        //@ts-ignore
                        this.__plotlyLayout.yaxis4.autorange = true;
                        //@ts-ignore
                        this.__plotlyLayout.yaxis5.autorange = true;
                        //@ts-ignore
                        this.__plotlyLayout.yaxis6.autorange = true;
                        //@ts-ignore
                        this.__plotlyLayout.yaxis7.autorange = true;
                        //@ts-ignore
                        this.__plotlyLayout.yaxis8.autorange = true;
                        //@ts-ignore
                        this.__plotlyLayout.yaxis9.autorange = true;


                        this.__liveData.splice(0, this.__liveData.length);
                        this.__traceIndices.splice(0, this.__traceIndices.length);


                        let columnsLength = this.__traces.map((trace: any) => { trace.data.value == true }).length;


                        this.__dataPoints = 10;
                        this.__bAddTrace = false;
                        this.__traces.forEach((_trace: any) => {
                            if (_trace.AddTrace == true) { this.__dataPoints = 3600; this.__bAddTrace = true; _trace.AddTrace = false;}
                        })

                        this.__traces.forEach((trace: any, index: any) => {

                            //Remove trace
                            if (trace.data.value == false)
                                Plotly.deleteTraces(this.__elementPlotlyRoot[0], index);
                            else if (trace.data.value == true)
                                    this.__updateLivePlot2(this.__symbols[trace.data.index].Name, this.__symbols[trace.data.index].Group, index, trace.data.index, columnsLength, this.__bAddTrace)
                        });


                    }


                }, 1000);
            /***************************************************************************************************
            * SQL Requests
            ***************************************************************************************************/
            private  __updateLivePlot2(columnName: any, tableName: any, index: number, _iIndex:number, length: number, bAddTrace: boolean) {

                this.__elementLoader.css('display', 'inline-block');
                

                var query;
                query = `select TOP ${this.__dataPoints} DateTime, ${columnName} from ${tableName}`


                Functions.getDataByQueryString(query)
                    .then(response => {
                        const responseData = [...response];
                        const dataSet = responseData.map((ds: any) => {
                            return {
                                x: ds.DateTime,
                                y: ds[columnName]
                            }
                        })
                        const x = dataSet.map((x: any) => x.x);
                        const y = dataSet.map((y: any) => y.y);


                        var plotdata = {
                            x: [x],
                            y: [y],
                            //type: 'scattergl',
                            //mode: 'lines',
                            //name: columnName,
                        }

                        this.__liveData.push(plotdata)

                        this.__traceIndices.push(index);
                        const yAxis = CommonFunctions.getPlotlyAxis(tableName);

                        if (this.__liveData.length == length) {

                            this.__liveData.forEach((livedata: any, indexxxx: any) => {
                                if (bAddTrace) {
                                    Plotly.plot(this.__elementPlotlyRoot[0], [livedata]);
                                    Plotly.extendTraces(this.__elementPlotlyRoot[0], livedata, [indexxxx], 3600);
                                }
                                else
                                    Plotly.extendTraces(this.__elementPlotlyRoot[0], livedata, [indexxxx], 3600);
                            })

                        }


                    })


            }
         public static getDataByQueryString = async function (queryString: string): Promise<string> {
                var callServer = function () {
                    return new Promise(resolve => {
                        // send request
                        TcHmi.Server.request(request, (data: TcHmi.Server.IResultObject<string, string>) => {
                            // check for server errors
                            if (data.error !== TcHmi.Errors.NONE) {
                                console.log("Server denied request");
                                console.log(data.error);
                                resolve('{"Error": "Server denied request"}');
                            }

                            // check response level error
                            if (data.response?.error !== undefined) {
                                console.log("Response level error");
                                resolve('{"Error": "Response level error"}');
                            }

                            // check request error
                            data.response?.commands?.forEach((command) => {
                                if (command.error !== undefined) {
                                    console.log("Request error", command);
                                    resolve('{"Error": "Request error"}');
                                }

                                responseBuffer.push(command.readValue as string);
                            });
                            resolve(JSON.parse(responseBuffer[0]));
                        })
                    })
                }
                const responseBuffer: Array<string> = new Array();

                // check if websocket is ready
                if (!TcHmi.Server.isWebsocketReady()) {
                    console.log("Websocket Error");
                    return "";
                }

                // Build Request object
                const request: TcHmi.Server.IReadWriteMessage<string, string> = {
                    requestType: "ReadWrite",
                    commands: [{
                        symbol: "TcHmiMSSQL.MaxRandomFromConfig",
                        commandOptions: ["SendErrorMessage"],
                        writeValue: queryString
                    }]
                }

                const result = await callServer();
                return result as string;
            }