chart.jsandroid-jetpack-composempandroidchart

How to implement a connected scatter graph in Chart.js


I am trying to implement the chart shown in Chart.js - essentially a scatter graph with two sets of connected data-sets. I have coded a scatter graph with the correct point distribution but struggle to find the way to implement the connected lines. The API shows options.elements.lines, but can this be applied to the Scatter type?

mock scatter


Solution

  • You can use the showLine property and make sure your data is in the correct order to make the dots connected:

    const options = {
      type: 'scatter',
      data: {
        datasets: [{
          data: [{
            x: 5,
            y: 6
          }, {
            x: 2,
            y: 9
          }, {
            x: 3,
            y: 4
          }, {
            x: 5,
            y: 6
          }],
          showLine: true
        }]
      },
      options: {
        scales: {}
      }
    }
    
    const ctx = document.getElementById('chartJSContainer').getContext('2d');
    new Chart(ctx, options);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.2.0/chart.umd.js"></script>
    
    <body>
      <canvas id="chartJSContainer" width="600" height="400"></canvas>
    </body>