Using Chart.Js to plot a scatter plot from an Array

Viewed 5450

I have written the following code:

<!DOCTYPE html>
<html lang = "en">
<head> 
    <meta charset = "UTF-8">
    <meta name = viewport" content ="width=device-width, intial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content = "ie=edge">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
    <link rel ="stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
    <title>My Chart.js</title>

</head>
<body> 
    <div class = "container">
        <canvas id="myChart"></canvas>
    </div>
    <script>
    var c = []; 
    var randomNumber = Math.random()*190;
        function getRandomDataPoint(x){
            if (x == "x"){
                var _return
                return Math.random()*20;
            }
            else if (x == "y"){
                return Math.random()*10 + randomNumber; 
            } 
            else{

            } 
        }
        var xPoints = [];
        var yPoints = [];
        var storage = [];
        for(var i=0;i<100;i++)
        { 
            xPoints[i] = Math.random()*20;
            yPoints[i] = Math.random()*10 + randomNumber;
            x = xPoints[i];
            y = yPoints[i];
            var json = {x: x, y: y};
            storage.push(json); 
        }

        var concatenatedArray = xPoints.concat(yPoints);



        let myChart = document.getElementById('myChart');//.getContext('2d');
        Chart.defaults.global.defaultColor = '#000000'; 

        let massPopChart = new Chart(myChart, {
            type: 'scatter',
                data: {
                    datasets: [{label: 'Data Set', data: [storage]}],
                },
                options: {
                    scales: {
                        yAxes: [{
                            ticks: {
                                max: 200,
                                min: 0,
                                beginAtZero:true
                            },
                        }]

                    }
                }       
        });

    </script>
</body>
</html>

What I would like for this code to do is take 100 random data points and plot them using the for-loop depicted in the code. The issue is the current set of code does create the axis however no data appears to be plotted. Thank you for any help.

Best Regards

1 Answers

The problem is in how you pass your data values to Chart.js on this line:

datasets: [{label: 'Data Set', data: [storage]}],

Specifically, data is supposed to be an array of objects. Because you have added the square brackets ([]) you are passing an 'array of array of objects'.

The problem can be fixed simply by removing the brackets:

data: storage
Related