Skip to content Skip to sidebar Skip to footer

How To Display Final Point Value In Charts.js

I'm using Charts.js library to display a line graph from data which is constantly updated. Is there a way to display only the final point value at all times? I want it to do this t

Solution 1:

Each time, a new value is available, you can simply remove outdated labels and dataset.data values once a certain limit is reached. This can be done using Array.shift(), which removes the first element from an array. Once these array are updated, you need to invoke chart.update().

var maxValues = 4;
setInterval(() => {
  chart.data.labels.push(new Date());
  chart.data.datasets[0].data.push(Math.floor((Math.random() * 20) + 1));
  if (chart.data.labels.length > maxValues) {
    chart.data.labels.shift();
    chart.data.datasets[0].data.shift();
  }
  chart.update();
}, 1000);

For displaying the value on the last added data point, you can use the Plugin Core API. It offers different hooks that may be used for executing custom code. In below runnable code snippet, I use the afterDraw hook to draw text directly on the canvas.

var chart = newChart('chart', {
  type: "line",
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];
      var iLastValue = chart.data.labels.length - 1;
      var lastValue = chart.data.datasets[0].data[iLastValue];
      var x = xAxis.getPixelForValue(chart.data.labels[iLastValue]);
      var y = yAxis.getPixelForValue(lastValue);
      ctx.save();
      ctx.textAlign = 'center';
      ctx.font = '14px Arial';
      ctx.fillStyle = "red";
      ctx.fillText('Value: ' + lastValue, x, y - 15);
      ctx.restore();
    }
  }],
  responsive: true,
  maintainAspectRatio: false,
  data: {
    labels: [],
    datasets: [{
      label: "Data",
      data: [],
      fill: false,
      lineTension: 0,
      backgroundColor: "white",
      borderColor: "red",
    }]
  },
  options: {
    layout: {
      padding: {
        right: 50
      }
    },
    scales: {
      xAxes: [{
        type: 'time',
        ticks: {
          source: 'auto'
        },
        time: {
          unit: 'second',
          displayFormats: {
            second: 'mm:ss'
          },
          tooltipFormat: 'mm:ss'
        },
      }],
      yAxes: [{
        ticks: {
          min: 0,
          max: 20,
          stepSize: 5
        }
      }]
    }
  }
});

var maxValues = 4;
setInterval(() => {
  chart.data.labels.push(newDate());
  chart.data.datasets[0].data.push(Math.floor((Math.random() * 20) + 1));
  if (chart.data.labels.length > maxValues) {
    chart.data.labels.shift();
    chart.data.datasets[0].data.shift();
  }
  chart.update();
}, 1000);
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script><canvasid="chart"height="90"></canvas>

Post a Comment for "How To Display Final Point Value In Charts.js"