Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

chart js 2 how to set bar width

I'm using Chart js version: 2.1.4 and I'm not able to limit the bar width. I found two options on stackoverflow

barPercentage: 0.5 

or

categorySpacing: 0 

but neither of one works with the mentioned version. Is there a way to solve this issue without manually modifying the chart.js core library?

thanks

like image 239
kiwi1342 Avatar asked Jun 16 '16 10:06

kiwi1342


People also ask

How do you adjust the width of a bar chart?

Click on any bar in the Bar Chart and right click on it, then select Format Data Series from the right-clicking menu. See screenshot: 2. In the popping up Format Data Series pane, move the Zoom bar of the Gap Width to the left side until the bar width meets your needs under the Series Options section.


2 Answers

You were right : The attribute you have to edit is barPercentage.

But maybe the error comes from where you edited the value.

As you can see in the bar chart options :

Name : barPercentage
- Type : Number
- Default : 0.9
- Description : Percent (0-1) of the available width each bar should be within the category percentage. 1.0 will take the whole category width and put the bars right next to each other. Read More

The attribute is actually stored in scales.xAxes ("Options for xAxes" table).

So you just have to edit your chart this way :

var options = {     scales: {         xAxes: [{             barPercentage: 0.4         }]     } } 


Here is a fully working example with a custom width (0.2) for the bar :

var data = {      labels: ["January", "February", "March", "April", "May", "June", "July"],      datasets: [{          label: "My First dataset",          backgroundColor: "rgba(75,192,192,0.4)",          borderColor: "rgba(75,192,192,1)",          data: [65, 59, 75, 81, 56, 55, 40],      }]  };    var ctx = document.getElementById("myChart");  var myChart = new Chart(ctx, {      type: 'bar',      data: data,      options: {          scales: {              yAxes: [{                  ticks: {                      beginAtZero: true                  }              }],              xAxes: [{                  // Change here              	barPercentage: 0.2              }]          }      }  });    console.log(myChart);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.js"></script>  <canvas id="myChart"></canvas>


Update (Chart.js Version 2.2.0+)

As stated in the Release Version 2.2.0 - Candidate 2 :

Enhancements

  • Can now manually configure the thickness of a bar in a bar chart. Use a new barThickness option on the correct axis to set the thickness of a bar.
  • And so on ...
like image 186
tektiv Avatar answered Oct 27 '22 22:10

tektiv


As of v2.7.2 it can be done by:

scales: {   xAxes: [{     maxBarThickness: 100,   }], } 
like image 34
Wei WANG Avatar answered Oct 27 '22 22:10

Wei WANG