gengns ES

An entry from the gengns log, written by Génesis García Morilla · · HTML5, JavaScript

Add extra info to samples’ tooltip

Starting from our JSON with an array of samples, we are going to set the names of each sample in its tooltip, respectively.

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);

HTML

<canvas id="myChart"></canvas>

CSS

#myChart {
  width: 100%;
  height: 100%;
}
Open in JSFiddle

Tags: canvas, Chartjs, line chart, tooltip