[Chartjs]-Creating a chart.js scatter graph with variables for data

1👍

You have some issues with setting up your code:

  1. You have not defined storage array
  2. console.log(chart) throws an error, you have to comment that line out or remove it
  3. The elements in your ABC array does not have 4 elements(arrays are 0 indexed and
    your last index will be 2 not 3)
    So this line var entery = {x: array[counter][0], y: array[counter][3]}; should be changed to var entery = {x: array[counter][0], y: array[counter][2]};

So, your code should look like this:

<html>

<head>
    <title>Test1</title>
    <script src="Chart.min.js"></script>
</head>
<body>
    <button onclick="addData();">Test</button>

    <script type="text/javascript">
        function addData(){
            ABC=[[1,2,1],[2,2,2],[3,3,3]];
            chart(ABC);
        }


        function chart(array)
        {
            var storage = [];
            for (counter = 0; counter < array.length; counter++) 
            {
                var entery = {x: array[counter][0], y: array[counter][2]};
                storage.push(entery);
            }

            document.write('<canvas id="lineChart" height="200" width="450"></canvas>');    

            const chart = document.getElementById("lineChart");
            //console.log(chart)
            var myChart = new Chart(chart, {
                type: 'scatter',
                data: {
                    datasets: [{
                        "fill":false,
                        pointRadius: 10,
                        label: 'Scatter Dataset',
                        data: storage        
                        }]
                },
                options: {
                    scales: {
                        xAxes: [{
                            type: 'linear',
                        }]
                    }
                }
            });
        }
    </script>
</body>
</html>

Also here you can find a working copy of the chart.

Leave a comment