inzi
inzi

Reputation: 83

How to change Chart.js horizontal bar chart Width?

I am trying to make the bars being generated by Chartjs.Horizontal thinner.

I tried changing calculateBarWidth to return a value from the options object being passed in.

When that didn't work, I tried hardcoding a value to return into calculateBarWidth (code below). However, that didn't work either.

Is there any other avenue I should explore in resolving this ?

Chart.Type.extend({
    name: "HorizontalBar",
    defaults : defaultConfig,
    initialize:  function(data){

        //Expose options as a scope variable here so we can access it in the ScaleClass
        var options = this.options;

        this.ScaleClass = Chart.Scale.extend({
            offsetGridLines : true,
            calculateBarX : function(datasetCount, datasetIndex, barIndex){
                var xWidth = this.calculateBaseWidth(),
                    xAbsolute = this.calculateX(barIndex) - (xWidth/2),
                    barWidth = this.calculateBarWidth(datasetCount);

                return xAbsolute + (barWidth * datasetIndex) + (datasetIndex * options.barDatasetSpacing) + barWidth/2;
            },
            calculateBaseWidth : function(){
                return (this.calculateX(1) - this.calculateX(0)) - (2*options.barValueSpacing);
            },
            calculateBarWidth : function(datasetCount){
                return 10;
            },
            // rest of code

Upvotes: 3

Views: 3632

Answers (2)

William Kennedy
William Kennedy

Reputation: 143

You can set it inside options object.

var options = 
{
    scales: 
    {
        yAxes: [
            {
                barPercentage: 0.3
            }]
    }
}

Upvotes: 1

potatopeelings
potatopeelings

Reputation: 41075

Just override the buildScale method to mess around with the scale object once its created.


Preview

enter image description here


Script

Chart.types.HorizontalBar.extend({
  name: "HorizontalBarAlt",
  initialize:  function(data){
    var originalBuildScale = this.buildScale;
    var chart = this;
    chart.buildScale = function() {
          var r = originalBuildScale.apply(this, arguments);
          chart.scale.calculateBarHeight = function() {
             return 10;
          }
          return r;
    }
    Chart.types.HorizontalBar.prototype.initialize .apply(this, arguments);
  }
});

Fiddle - http://jsfiddle.net/2mtgsoy3/

Upvotes: 2

Related Questions