Add extra info to samples' tooltip

Line chart

by Génesis García Morilla

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.js"></script>
<canvas id="myChart"></canvas>

CSS

#myChart {
  width: 100%;
  height: 100%;
}

JavaScript

const data = [{
  "name": "Pablo",
  "date": "2097-06-24 00:00:00",
  "value": 80
}, {
  "name": "Chani",
  "date": "2097-06-24 04:00:00",
  "value": 70
}, {
  "name": "Javi",
  "date": "2097-06-24 18:00:00",
  "value": 40
}, {
  "name": "Marta",
  "date": "2097-06-24 22:00:00",
  "value": 80
}, {
  "name": "Paqui",
  "date": "2097-06-24 23:10:00",
  "value": 100
}]

const chart = (() => {
  /**
   * Load data
   * @param data [array]
   */
  function load(data) {
    const ctx = document.getElementById("myChart").getContext('2d');

    let myChart = new Chart(ctx, {
      type: 'line',
      data: {
        datasets: [{
          label: 'Value',
          data: data.map(m => {
            return {
              x: m.date,
              y: m.value
            }
          }),
          steppedLine: true,
          backgroundColor: 'rgba(255, 153, 0, 0.2)',
          borderColor: 'rgba(255, 153, 0, 1)',
          borderWidth: 2
        }]
      },
      options: {
        responsive: true,
        title: {
          display: true,
          text: 'Chart'
        },
        tooltips: {
          enabled: true,
          mode: 'single',
          callbacks: {
            label: function(tooltipItems) {
              const {
                index,
                yLabel
              } = tooltipItems;
              return ` ${data[index].name} value is ${yLabel}`;
            }
          }
        },
        scales: {
          xAxes: [{
            type: 'time',
            display: true,
            scaleLabel: {
              display: true,
              labelString: 'Date'
            }
          }],
          yAxes: [{
            display: true,
            stacked: true,
            scaleLabel: {
              display: true,
              labelString: 'Value'
            }
          }]
        }
      }
    });
  }

  return {
    load: load
  };
})();

chart.load(data);