Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ChartJs bar chart - keep bars left instead of equally spread across the width

I'm using ChartJs 2.7.2 to draw a simple bar chart. In my app, the number of bars will vary between 5 - 15. By default the bars are equally distributed across the full width of the chart. However, I want the bars to have a fixed width/left aligned (so when only 5 bars, they do not take up the full width, but stay left aligned). Please see below screenshot for clarification.

enter image description here

like image 902
Stijn V Avatar asked Sep 11 '18 15:09

Stijn V


People also ask

What is a sideways Barchart called?

It is also known as a clustered bar graph or a multi-set bar chart. In simple terms, a horizontal grouped bar chart uses horizontal bars to represent and compare different data categories of 2 or more groups.

How do you change the width of a bar plot?

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.

Do bar charts have gaps between bars?

A standard bar chart should have gaps between bars that are slightly narrower than the bars. The exceptions to this are the exception of histograms and clustered bar charts.


1 Answers

You can provide a labels array padded with empty strings to the required length, e.g. 15.

This will ensure a consistent number of categories on the axis, and thus ensure that the bars will stay the same width and left-aligned even when there are less bars (Fiddle).

(If you like, you can also pad the data array with 0's for consistency, but it's not necessary - the labels array is what determines the axis looks like.)

var data = [12, 19, 3, 5, 2];
var labels = ["a", "b", "c", "d", "e"];

for (var i = labels.length; i < 15; i++) {
  labels.push("");
}

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: labels,
    datasets: [{
      label: 'Count',
      data: data
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  } 
});
like image 59
sheilak Avatar answered Oct 19 '22 01:10

sheilak