[Chartjs]-How to make chartJs stacked bar always rounded when data is 0?

1๐Ÿ‘

I have updated your Fiddle only line number 118:
https://jsfiddle.net/r7hvn2ox/

From:

if (rounded){

To:

if (rounded || this._chart.data.datasets[1].data[this._index] == 0) {

I know its fix for 2 datasets: [{}, {}] bars, but it will work perfectly in any of the values of datasets and also for this example.

1๐Ÿ‘

Thanks everyone for answers.I tried below and worked perfectly for any amount of datasets.

var lastVisible;
  var datasetsLength = this._chart.data.datasets.length;
  this._chart.data.datasets.map((e,index)=>{
    lastVisible=datasetsLength-1;
    //to find the depth of datasets and get non-zero value
    for(var i=lastVisible;i>0;i--){
    if(!this._chart.getDatasetMeta(i).hidden){
      if(this._chart.data.datasets[i].data[this._index] != 0){
        lastVisible = i;
        break;
      }
    }
    } 
  })

0๐Ÿ‘

You could add an additional expression to rounded variable if its rendering specific item. This is not the best approach.

var rounded = this._datasetIndex  === lastVisible || this._index === 2;

Alternatively you could compare values in each dataset

var cond = false;

if(this._datasetIndex === 0) {
  var datasets = this._chart.data.datasets;
  var dataset = datasets[this._datasetIndex];
  var currentData = dataset.data[this._index];
  var nextData = datasets[this._datasetIndex + 1].data[this._index]
  cond = currentData !== 0 && nextData === 0;
}

var rounded = this._datasetIndex  === lastVisible || cond;

Leave a comment