[Chartjs]-Display gaps between the timestamps having no data in ChartJS time series

1👍

Since v3 chart.js has an ability to set spanGap as a number, determining the maximum gap to span. So in this case, 1 hour gap can be used in order to keep the data points connected, but at the same time have a gap between 11pm and 5 am

Docs: https://www.chartjs.org/docs/latest/charts/line.html#line-styling

Official example: https://www.chartjs.org/docs/latest/samples/scales/time-max-span.html

Here’s the adjusted code:

const ctx = document.getElementById('chart');

const data = [{
    "y": "0.58",
    "x": 1565665819571,
  },
  {
    "y": "0.84",
    "x": 1565665218436,
  },
  {
    "y": "1.69",
    "x": 1565664625228
  },
  {
    "y": "0.24",
    "x": 1565640019245
  },
  {
    "y": "0.24",
    "x": 1565639418937
  },
  {
    "y": "0.25",
    "x": 1565638819713
  },
  {
    "y": "0.25",
    "x": 1565638219190
  },
  {
    "y": "0.23",
    "x": 1565637619961
  },
  {
    "y": "0.24",
    "x": 1565637018574
  },
  {
    "y": "0.24",
    "x": 1565636426432
  },
  {
    "y": "0.24",
    "x": 1565635825187
  },
  {
    "y": "0.25",
    "x": 1565635218607
  },
  {
    "y": "0.25",
    "x": 1565634618853
  },
  {
    "y": "0.26",
    "x": 1565634020604
  },
  {
    "y": "0.26",
    "x": 1565633419088
  },
  {
    "y": "0.27",
    "x": 1565632819216
  },
  {
    "y": "0.27",
    "x": 1565632218830
  },
  {
    "y": "0.28",
    "x": 1565631620692
  },
  {
    "y": "0.29",
    "x": 1565631019620
  },
  {
    "y": "0.29",
    "x": 1565630418738
  },
  {
    "y": "0.30",
    "x": 1565629818050
  },
  {
    "y": "0.31",
    "x": 1565629218872
  },
  {
    "y": "0.33",
    "x": 1565628126871
  }

]

const chart = new Chart(ctx, {
  "type": "line",
  "data": {
    datasets: [{
      label: 'Foo',
      backgroundColor: "lightblue",
      borderColor: "blue",
      fill: false,
      data: data,
      pointRadius: 0,
      spanGaps: 1000 * 60 * 60, // 1 hour
    }]
  },
  options: {
    responsive: true,
    scales: {
      xAxis: {
        type: "time"
      }
    },
    "tooltips": {
      "intersect": false,
      "mode": "index",
      "callbacks": {}
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.2.0/chart.umd.js"></script>
<script src="https://cdn.jsdelivr.net/npm/luxon@^2"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon@^1"></script>
<canvas id="chart"></canvas>

Leave a comment