score:7

Accepted answer

there is no way to configure chart.js to do this, but you could use a hack instead. just set your value for the 0 bar to a really small number like 0.1.

data: [2, 0.1, 3, 1]

here is an example forked from yours.

if you are using tooltips, then you would have to also add some logic so that the tooltip for that bar still displays a value of 0. you can do this using the label callback.

label: function(tooltipitem, data) {
  var value = data.datasets[0].data[tooltipitem.index];
  var label = data.labels[tooltipitem.index];

  if (value === 0.1) {
    value = 0;
  }

  return label + ': ' + value + ' %';
}

here is an example putting it all together.

score:1

i just stumbled over this questions because i had a similar problem: the type of my chart.js chart was 'horizontalbar' and for some datasets (where no zero values was present across the dataset) the horizontal bar did not start with 0 rather with the lowest value from the dataset.

i tried to figure out a solution and came up with following entry in the options object while creating the charts:

ticks: {
                  beginatzero:true,
                  mirror:false,
                  suggestedmin: 0,
                  suggestedmax: 100
} 

however that did not work as expected although all posts said it works that way. after further investigation and reading of the chart.js documentation i found the solution. the reason the further step did not work was following i found in the documentation:

however, any options specified on the x axis in a bar chart, are applied to the y axis in a horizontal bar chart.

so i just changed my options object to hold the proper configuration for the xaxes and it worked.

for those who are interested here is the the whole code i used for creating the horizontal bar chart with y-axis starting always at zero:

this.chart = new chart(
    ctx,
    {
        type: 'horizontalbar',
        data: this.data.chartdata,
        options: {
          scales: {
              xaxes: [{ 
                stacked: false,
                ticks: {
                  beginatzero:true,
                  mirror:false,
                  suggestedmin: 0,
                  suggestedmax: 100
                } 
              }],
              yaxes: [{ 
                stacked: true
              }]
          },
          scalebeginatzero : true,
          // important here to use () =>
          // to keep the scope of this
          onclick: (e) => {
            var actchart : chart = this.charts[trialid];
            var element =
              actchart.getelementatevent(e);

            }
        }
    }
);

score:1

here is the simplest way to do this in v3 chart js

chart.defaults.datasets.bar.minbarlength = 5;

score:2

2019 update

this can be done easily as below.

var mychart = new chart(ctx, {
    ...
    options: {
        ...
        scales: {
            yaxes: [{
                ticks: {
                    beginatzero: true
                }
            }]
        }
    }
);

you can find this in chart.js documentation https://www.chartjs.org/docs/latest/

score:3

if you struggle with this, here's what i came up with. it is similar idea to li jinyao, but in addition, you would get click and hover events (tooltip) working for whole bar. i value is close to 0 but negative, the bar will show on negative side of x axis - you can easily get rid of it if that's not what you want to do.

const zerocompensation = {
id: 'zerocompensation',

beforedatasetsdraw: function(chart) {
    const meta = chart.getdatasetmeta(0)
    foreach(meta.data, d => {
        const barheight = d._view.base - d._view.y;
        if(math.abs(barheight) < minbarheight /* i used value 5 */) {
            d._view.y = d._view.base - minbarheight * (math.sign(barheight) || 1);
        }
    });
}};

and add it to plugins:

plugins: [zerocompensation]

keep in mind that this will work for values close to 0, not only 0. if you want it only for zeroes, you can change contents of if condition to:

chart.config.data.datasets[0].data[index] === 0

this is what li jinyao used in his answer. hope that helps.
edit: i wanted to highlight that this solution works regardless of values spread. answer marked as solution will not work as intended if there are some high values in data set - 0.1 will render same as 0 in that case.

score:15

after dig into the plugin system, if you using chart.js >=2.5, you can write a plugin to achieve it. here is an example to draw a line when data is zero.

enter image description here

here is my code:

const zerocompensation = {
  renderzerocompensation: function (chartinstance, d) {
      // get postion info from _view
      const view = d._view
      const context = chartinstance.chart.ctx

      // the view.x is the centeral point of the bar, so we need minus half width of the bar.
      const startx = view.x - view.width / 2
      // common canvas api, check it out on mdn
      context.beginpath();
      // set line color, you can do more custom settings here.
      context.strokestyle = '#aaaaaa';
      context.moveto(startx, view.y);
      // draw the line!
      context.lineto(startx + view.width, view.y);
      // bam! you will see the lines.
      context.stroke();
  },

  afterdatasetsdraw: function (chart, easing) {
      // get data meta, we need the location info in _view property.
      const meta = chart.getdatasetmeta(0)
      // also you need get datasets to find which item is 0.
      const dataset = chart.config.data.datasets[0].data
      meta.data.foreach((d, index) => {
          // for the item which value is 0, reander a line.
          if(dataset[index] === 0) {
            this.renderzerocompensation(chart, d)
          }
      })
  }
};

and here is how to add the plugin to chart.js

var chart1 = new chart(ctx, {
    plugins: [zerocompensation]
});

the offcial document is not clear about their plugin api, you may console.log to find what you want.

score:16

simply specify minbarlength in the dataset, with the minimum length in pixels the bars should have. see documentation.

working example:

var $chartcanvas = $('mycanvas');
var barchart = new chart(mycanvas, {
    type: 'bar',
    data: {
        labels: ['accepted answer', 'top rated answer', 'this answer'],
        datasets:[{
            data: [0, 3, 10],
            minbarlength: 7,    // this is the important line!
        }]
    },
    options: {
        title: {
            display: true,
            text: 'helpfulness of answers to this questions'
        },
        legend: {
            display: false
        }
    }
});
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="mycanvas"></canvas>


Related Query

More Query from same tag