Chartjs-Formatting Data With Charts.JS

0πŸ‘

βœ…

In side the animation.onComplete function, change the line that writes the text to the canvas as follows.

// ctx.fillText(data, bar._model.x, bar._model.y - 5); // old
ctx.fillText('$' + data.toLocaleString(), bar._model.x, bar._model.y - 5); // new

Please have a look at your amended code below:

var canvas = document.getElementById('myChart');
var data = {
  labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
  datasets: [{
    label: "Testing Charts.js",
    backgroundColor: "rgba(255,0,0,1)",
    borderColor: "rgba(255,0,0,1)",
    borderWidth: 2,
    hoverBackgroundColor: "rgba(255,99,132,0.4)",
    hoverBorderColor: "rgba(255,99,132,1)",
    data: [230607.44, 191058.97, 234336.08, 215685.54, 213641.96, 244680.33, 227620.03, 235005.76, 233183.45, 205075.22, 190864.84, 231137.39],
  }]
};
var option = {
  tooltips: {
    callbacks: {
      label: function(t, d) {
        if (t.datasetIndex === 0) {
          var xLabel = d.datasets[t.datasetIndex].label;
          var yLabel = t.yLabel + '%';
        } else if (t.datasetIndex === 1) {
          var xLabel = d.datasets[t.datasetIndex].label;
          var yLabel = t.yLabel >= 1000 ? '$' + t.yLabel.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") : '$' + t.yLabel;
          return xLabel + ': ' + yLabel;
        }
      }
    }
  },
  scales: {
    yAxes: [{
      ticks: {
        beginAtZero: true,
        callback: function(value, index, values) {
          if (parseInt(value) >= 1000) {
            return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
          } else {
            return '$' + value;
          }
        }
      }
    }]
  },
  animation: {
    duration: 5000,
    onComplete: function() {
      var chartInstance = this.chart,
        ctx = chartInstance.ctx;
      ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
      ctx.textAlign = 'center';
      ctx.textBaseline = 'bottom';
      this.data.datasets.forEach(function(dataset, i) {
        var meta = chartInstance.controller.getDatasetMeta(i);
        meta.data.forEach(function(bar, index) {
          var data = dataset.data[index];
          ctx.fillText('$' + data.toLocaleString(), bar._model.x, bar._model.y - 5);
        });
      });
    }
  }
};

var myBarChart = Chart.Bar(canvas, {
  data: data,
  options: option
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="200"></canvas>

Leave a comment