ae3e-plotly-panel icon indicating copy to clipboard operation
ae3e-plotly-panel copied to clipboard

JS Library Import

Open sebas1986 opened this issue 2 years ago • 2 comments

Hi,

what is the best way to import a JS Library to use in the Script part? An example for me would be the following library to create scatter plot fitting:

https://github.com/HarryStevens/d3-regression

Thanks,

Sebastian

sebas1986 avatar Apr 26 '22 15:04 sebas1986

I would also be interested in how to do this! Anybody got any thoughts on this?

antczakp avatar Jun 09 '22 09:06 antczakp

Hey, can't answer on how to import a library, but I have managed to get linear regression plotted on a scatter plot. This is the contents of my Script field:

console.log(data)

function linearRegression(x,y){
        var lr = {};
        var n = y.length;
        var sum_x = 0;
        var sum_y = 0;
        var sum_xy = 0;
        var sum_xx = 0;
        var sum_yy = 0;

        for (var i = 0; i < y.length; i++) {

            sum_x += x[i];
            sum_y += y[i];
            sum_xy += (x[i]*y[i]);
            sum_xx += (x[i]*x[i]);
            sum_yy += (y[i]*y[i]);
        } 

        lr['sl'] = (n * sum_xy - sum_x * sum_y) / (n*sum_xx - sum_x * sum_x);
        lr['off'] = (sum_y - lr.sl * sum_x)/n;
        lr['r2'] = Math.pow((n*sum_xy - sum_x*sum_y)/Math.sqrt((n*sum_xx-sum_x*sum_x)*(n*sum_yy-sum_y*sum_y)),2);

        return lr;
}

var x_data_64 = data.series[0].fields[0].values.buffer;
var y_data_64 = data.series[0].fields[1].values.buffer;
var lr = linearRegression(x_data_64, y_data_64);
//console.log(lr);

var trace = {x: x_data_64,
            y: y_data_64,
            name: "Scatter",
            marker: { size: 10 }
            };  
//console.log(trace);

var fit_from = Math.min(...x_data_64)
var fit_to = Math.max(...x_data_64)

var fit = {
  x: [fit_from, fit_to],
  y: [fit_from*lr.sl+lr.off, fit_to*lr.sl+lr.off],
  mode: 'lines',
  type: 'scatter',
  name: "R2=".concat((Math.round(lr.r2 * 10000) / 10000).toString())
};

//console.log(fit);
return {data:[trace,fit],layout:{hovermode:'closest',title:'My Scatterplot'}};

danrichter-8451 avatar Jun 23 '22 13:06 danrichter-8451