Skip to main content Skip to footer

How To: Change the Width of a Bar in Wijmo Bar Chart

When there are multiple charts on a page having different number of bars in each, then, the width of bars vary in each chart. This is because the width of a bar is directly dependent on the number of datapoints(bars) in a dataseries. That means, if a barchart has 2 datapoints then the bars will be thicker as compared to the width of bars in a chart having 6 datapoints. The charts will look like: This blogs explains how you can change the default width for each bar in wijmo barchart so that you can have bars with a consistent width in all the charts. To start off, you can create a wijbarchart by setting few properties in jQuery and may refer to the online demo for this. In order to set width of each bar, we can access the bar using getBar method of the WijBarChart. Now, we can set the width of this bar to any custom value using its attributes. Please note, since we are changing the width, we also need to change its x position so that bar is displayed correctly. The code given below would help you in achieving the same:

var seriesElements = $("#wijbarchart2").wijbarchart().data().fields.seriesEles;  
//loop through the serieslist  
$.each(seriesElements, function (index, series) {  
   //custom value which we want to set  
   var newWidth = 75;  
   //loop through datapoints of each series  
   $.each(series, function (counter, datapoint) {  
      //get the bar object  
      var barObj = $("#wijbarchart2").wijbarchart('getBar', counter);  
      //calculate its centre  
      var centre = barObj.attrs.x + barObj.attrs.width / 2;  
      //calculate and set the new x-positon  
      var newX = centre - newWidth / 2;  
      barObj.attr('x', newX);  
      //set the custom width  
      barObj.attr('width', newWidth);  
      barObj.width = newWidth;  
      $("#wijbarchart2").find("rect:eq(" + counter + ")").attr("stroke-width", 0);  
    });  
 });

You may also checkout this sample implementing the same.

MESCIUS inc.

comments powered by Disqus