Chartjs-Chart.js: stack the bars to the left

0👍

Instead of creating a graph with 10 empty bar charts, then populate it with your values, I think it would be better to add empty values to reach the number of 10 (same idea though).

If you take a look in the Chart.js documentation, you can see that you can create plugins for your charts and graphs. Plugins are extremely useful when editing your chart (instead of just hardcoding what you want) since they allow you to handle what is happening while creating your charts.
For instance : beforeUpdate, afterDraw are some of the events you can handle with plugins.


Now, you must know that the chart object contains a lot of information :

  • If you want to edit a global option, you’d check chart.config.options
  • If you want to edit a specific chart, you’d check chart.config.data

In our case, we’d need the data attribute.
If you take a deep look in it, you’d see that the number of values come from the lengh of both data.labels and data.datasets[n].data (n being the nth dataset).


Now that you know what to do, and how to do it, you can do it.

I still made a quick example of what you are looking for :

var ctx = document.getElementById("myChart").getContext("2d");

// stores the number of bars you have at the beginning.
var length = -1;

// creates a new plugin
Chart.pluginService.register({

  // before the update ..
  beforeUpdate: function(chart) {
    var data = chart.config.data;
    for (var i = data.labels.length; i < data.maxBarNumber; i++) {
      length = (length == -1) ? i : length;
      // populates both arrays with default values, you can put anything though
      data.labels[i] = i;
      data.datasets[0].data[i] = 0;
    }
  },

  // after the update ..
  afterUpdate: function(chart) {
    console.log(chart);
    var data = chart.config.data;
    if (length == -1) return;

    // prevents new charts to be drawn
    for (var i = length; i < data.maxBarNumber; i++) {
      data.datasets[0]._meta[0].data[i].draw = function() {
        return
      };
    }
  }
});

var data = {

  // change here depending on how many bar charts you can have
  maxBarNumber: 10,
  labels: [1, 2, 3, 4, 5, 6, 7],
  datasets: [{
    label: "dataset",
    backgroundColor: 'rgba(255, 99, 132, 0.2)',
    borderColor: 'rgba(255,99,132,1)',
    borderWidth: 1,
    data: [65, 59, 80, 81, 56, 55, 40],
  }]
};

var myBarChart = new Chart(ctx, {
  type: 'bar',
  data: data,
  options: {
    scales: {
      xAxes: [{
        display: false
      }],
      yAxes: [{
        stacked: true
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.1/Chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>

0👍

You can use Array.prototype.reverse() to reverse the data if it is currently stacked to the right. Otherwise you will need to use some type of sorting to go from largest data to smallest data.

Leave a comment