Chart.js bar chart barWidth is Inconsistent

👍:0

What’s happening is your fixed barValueSpacing is horizontally flipping over your bars (your right edge of the bar becomes the left edge and vice versa) once the chart width becomes small enough. You need to dynamically set the barValueSpacing based on the chart width by extending the bar chart type.

Here’s how you do it

var a = [1, 2, 3];
var data = {
    labels: ["A", "B", "C"],
    datasets: [{
        label: "My dataset",
        fillColor: "rgba(151,187,205,0.2)",
        strokeColor: "rgba(151,187,205,1)",
        pointColor: "rgba(151,187,205,1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(151,187,205,1)",
        data: a
    }]
};

Chart.types.Bar.extend({
    name: "BarAlt",
    draw: function(){
        this.options.barValueSpacing = this.chart.width / 5;
        Chart.types.Bar.prototype.draw.apply(this, arguments);
    }
});

And the fiddle – http://jsfiddle.net/9avv76vx/

The top one is the resized bar and the bottom one is the normal bar – I’ve divided the chart width by a constant (5), but in real life you’ll need to take the number of data points into consideration and divide by a suitable fraction of that.

Leave a comment