[Chartjs]-Is there a way in chartjs to display different Boolean values with an offset in Y over a common timeline?

1👍

You could do this by shifting the y-values of individual datasets. If you have 3 datasets for example, the values would be generated as follows:

dataset 1: false: -0.1 / true: 0.9
dataset 2: false: 0 / true: 1
dataset 3: false: 0.1 / true: 1.1

Please have a look at below runnable code snippet.

var chart = new Chart('myChart', {
  type: 'line',
  data: {
    datasets: [{
      label: 'A',
      data: [
          { x: "2020-06-07 08:51:22", y: -0.1 },
          { x: "2020-06-07 09:22:01", y: 0.9 },
          { x: "2020-06-07 09:37:28", y: -0.1 },
          { x: "2020-06-07 10:10:51", y: 0.9 },
          { x: "2020-06-07 11:42:54", y: 0.9 }
      ],
      borderColor: 'green',
      fill: false,
      steppedLine: 'before'
    },
    {
      label: 'B',
      data: [
          { x: "2020-06-07 08:45:17", y: 0 },
          { x: "2020-06-07 09:30:17", y: 1 },
          { x: "2020-06-07 10:15:16", y: 0 },
          { x: "2020-06-07 11:00:17", y: 1 },
          { x: "2020-06-07 12:15:16", y: 0 }
      ],
      borderColor: 'red',
      fill: false,
      steppedLine: 'before'
    },
    {
      label: 'C',
      data: [
          { x: "2020-06-07 09:00:28", y: 1.1 },
          { x: "2020-06-07 09:15:44", y: 0.1 },
          { x: "2020-06-07 10:41:05", y: 1.1 },
          { x: "2020-06-07 11:22:18", y: 0.1 },
          { x: "2020-06-07 12:33:54", y: 1.1 }
      ],
      borderColor: 'blue',
      fill: false,
      steppedLine: 'before'
    }]
  },
  options: {
    tooltips: {
      callbacks: {
        label: tooltipItem => tooltipItem.value < 0.5 ? 'false' : 'true'
      }
    },
    scales: {
      xAxes: [{
        type: 'time',
        time: {
          unit: 'minute',
          displayFormats: {
            minute: 'HH:mm'            
          },
          tooltipFormat: 'HH:mm'
        },
        ticks: {
          source: 'data',
          minRotation: 45
        },
        gridLines: {
          drawOnChartArea: false
        }
      }],
      yAxes: [{
        ticks: {
          min: -0.3,
          max: 1.3,
          fontSize: 16,
          fontStyle: 'bold',
          callback: value => {
            if (value == 0) {
              return 'off';
            } else {
              return value == 1 ? 'on' : '';
            }
          }  
        },
        gridLines: {
          display: false
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="70"></canvas>

Leave a comment