Chartjs-Display data on chart.s

0👍

Using a scatter chart is a good choice. The solution however depends on the format of your data. Let’s presume, it looks like this:

const data = [
  { name: 'Rachel', calls: ['2021-03-01 10:15', '2021-03-01 18:02', '2021-03-02 06:48'] },
  { name: 'William', calls: ['2021-03-01 13:24', '2021-03-02 08:41', '2021-03-02 11:13'] },
  { name: 'Barbara', calls: ['2021-03-01 07:58', '2021-03-01 15:47', '2021-03-02 10:16'] }
];   

You need to create a dataset for each user and provide the data in point format where the values of distinct users are different but all values of a same user are identical. This can be done using the Array.map() method as follows:

data.map((user, i) => ({ 
  label: user.name,
  data: user.calls.map(call => ({ x: call, y: i + 1 }))
}))

Now you also need to define a ticks.callback function on the y-axis that transforms the numeric tick value back to the user name

yAxes: [{
  ticks: {
    ...
    callback: v => v % 1 == 0 ? data[v - 1].name : undefined
  }
}],

Please take a look at below runnable code and see how it works.

const data = [
  { name: 'Rachel', calls: ['2021-03-01 10:15', '2021-03-01 18:02', '2021-03-02 06:48'] },
  { name: 'William', calls: ['2021-03-01 13:24', '2021-03-02 08:41', '2021-03-02 11:13'] },
  { name: 'Barbara', calls: ['2021-03-01 07:58', '2021-03-01 15:47', '2021-03-02 10:16'] }
];
const colors = ['red', 'blue', 'green'];

new Chart('myChart', {
  type: 'scatter',
  data: {
    datasets: data.map((user, i) => ({ 
      label: user.name,
      data: user.calls.map(call => ({ x: call, y: i + 1 })),
      backgroundColor: colors[i],
      pointRadius: 4
    }))
  },
  options: {
    responsive: true,
    tooltips: {
      callbacks: {
        title: tooltipItem => data[tooltipItem[0].datasetIndex].name,
        label: tooltipItem => tooltipItem.xLabel
      }
    },
    scales: {   
      yAxes: [{
        ticks: {
          min: 0.5,
          max: data.length + 0.5,
          stepSize: 0.5,
          callback: v => v % 1 == 0 ? data[v - 1].name : undefined
        }
      }],
      xAxes: [{
        type: 'time',
        time: {
          unit: 'hour',
          displayFormats: {
            hour: 'MMM-DD HH'
          },
          tooltipFormat: 'MMM-DD HH:mm'
        },
        gridLines: {
          lineWidth: 0
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script>
<canvas id="myChart" height="80"></canvas>

Leave a comment