Unbreakable Unbreakable - 3 months ago 14
Javascript Question

How to create a stacked graph using ChartJS

As of now I have successfully created a line graph using ChartJS. But I want to make it stacked graph.

Below is what I have till now:

define(['backbone'], function(Backbone)
{
var fifthSubViewModel = Backbone.View.extend(
{
template: _.template($('#myChart5-template').html()),

render: function(){
$(this.el).html(this.template());
var ctx = this.$el.find('#lineChart5')[0];
var lineChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
datasets: [{
label: "Unavailable Unit",
backgroundColor: "rgba(38, 185, 154, 0.31)",
borderColor: "rgba(38, 185, 154, 0.7)",
pointBorderColor: "rgba(38, 185, 154, 0.7)",
pointBackgroundColor: "rgba(38, 185, 154, 0.7)",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointBorderWidth: 1,
data: this.model.attributes.unavailThisYear
}, {
label: "Vacant Unit",
backgroundColor: "rgba(3, 88, 106, 0.3)",
borderColor: "rgba(3, 88, 106, 0.70)",
pointBorderColor: "rgba(3, 88, 106, 0.70)",
pointBackgroundColor: "rgba(3, 88, 106, 0.70)",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(151,187,205,1)",
pointBorderWidth: 1,
data: this.model.attributes.vacThisYear
}]
},
options: {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Income in $'
}
}]
}
}
});
},
initialize: function(){
console.log("In the initialize function");
this.listenTo(this.model, 'change', this.render);
this.listenTo(this.model, 'destroy', this.remove);
this.render();
}
});

return fifthSubViewModel;
});


Currently, I am getting two line graph on a single chart. But I somehow want to make them stacked. I mean the second line graph starting point should be the place from where the first line graph. So, the area should not overlap. Is there any way I can tell that to my line chart to start from the value where the other line chart is ending so as to get a stacked graph.

Current Screenshot not stacked:

enter image description here

Answer

According to the docs of latest chartjs version, you need to set the stacked property to true in the axis you want to stack them. So in your case it would be:

       options: {
          scales: {
            yAxes: [{
              scaleLabel: {
                display: true,
                labelString: 'Income in $'
              },
              stacked: true
            }]
          }
        }

For more information go to ChartJs Docs