[Chartjs]-How to create a chart.js scatter chart with data from two lists

3👍

From the docs to use a scatter chart, data must be passed as objects containing X and Y properties.

You have to make sure the lists you are passing are in the correct format to be accepted by a scatter chart i.e.

var data = [{ x: -8, y: 3 }, { x: 2, y: 8 }, { x: 3, y: 9 }];

I would combine your two lists into one object then pass it to the chart.

let coords = pvols.map( (v,i) => ({ x: v, y: prets[i] }) )

Then pass that when you initilaize your chart

var data = [{ x: -8, y: 3 }, { x: 2, y: 8 }, { x: 3, y: 9 }];

var ctx = document.getElementById("chart");
var scatterChart = new Chart(ctx, {
  type: "scatter",
  data: {
    datasets: [
      {
        label: "Scatter Dataset",
        data: data
      }
    ],
    options: {
      scales: {
        xAxes: [
          {
            type: "linear",
            position: "bottom"
          }
        ]
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.js"></script>
<canvas id="chart" height="450" width="600"></canvas>

Leave a comment