Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show thousand in k format for bar values in chart.js

I have many bars with a thousand values like 35000, 12000, and 76560. So these values are getting overlapped with each other. I need to change Bar values not StepSize.

I want to show these values 35k, 12k and 76.5k format. This is my code

public barStatus() {
  var colors = ['#299DFF', '#80FFFF', '#F8362B', ];
  var chBar = document.getElementById("chBar");
  var chartData = {
    datasets: [{
      label: 'Success',
      data: [35000, 12000, 76560],
      backgroundColor: colors[0]
    }, ]
  }
  var barOptions_stacked = {
    onClick: this.Status,
    tooltips: {
      enabled: true
    },
    plugins: {
      datalabels: {
        anchor: 'end',
        align: 'left',
        formatter: Math.round,
        font: {
          color: 'black'
        }
      },
    },
    hover: {
      animationDuration: 0
    },
    scales: {
      xAxes: [{
          barPercentage: 0.5,
          categoryPercentage: 0.5
        }
      ],
      yAxes: [{
        gridLines: {
          display: false
        },
        type: 'logarithmic',
        position: 'left',
        ticks: {
          min: 0, //minimum tick
          max: 100000, //maximum tick
          callback: function (value, index, values) {
            return Number(value.toString()); //pass tick values as a string into Number function
          }
        },
        afterBuildTicks: function (chartObj) { //Build ticks labelling as per your need
          chartObj.ticks = [];
          chartObj.ticks.push(0);
          chartObj.ticks.push(10);
          chartObj.ticks.push(100);
          chartObj.ticks.push(1000);
          chartObj.ticks.push(10000);
          chartObj.ticks.push(100000);
        },
        scaleLabel: {
          display: false
        },
        stacked: false
      }]
    },
  };
  this.Canvas = document.getElementById("chBar");
  this.chart = new Chart(this.Canvas, {
    type: "bar",
    data: chartData,
    options: barOptions_stacked
  });
}

How can I do that?

Screenshot:

enter image description here

like image 705
R15 Avatar asked Oct 17 '25 16:10

R15


1 Answers

You need to pass a function in formatter option inside datalabels plugin configuration:

 datalabels: {
        anchor: "end",
        align: "left",
        formatter: function(context) {
          return context / 1000 + "k";
        },
        font: {
          color: "black"
        }
      }

You can check the solution in this demo: https://stackblitz.com/edit/angular-chart-js-thousand?file=src/app/app.component.ts

like image 162
Antonio Vida Avatar answered Oct 20 '25 05:10

Antonio Vida