ThisIsLegend1016
ThisIsLegend1016

Reputation: 105

Creating a stacked budget Vs Actual chart

I am trying to use chartJS to create a stacked budget with an actual vs budgeted amount.

So I am aiming to create something like this.

Stacked

I have gotten this far with it.

new Chart(document.getElementById("chartjs-7"), {
  "type": "bar",
  "data": {
    "labels": ["Petrol", "Food", "Kids Clubs", "Alcohol"],
    "datasets": [{
      "label": "Actual Spend",
      "data": [70, 100, 20, 29],
      "borderColor": "rgb(63, 191, 63)",
      "backgroundColor": "rgba(63, 191, 63)"
    }, {
      "label": "Budgeted amount",
      "data": [60, 150, 20, 30],
      "type": "bar",
      "fill": false,
      "borderColor": "rgb(63, 65, 191)",
      "backgroundColor": "rgba(63, 65, 191)"
    }]
  },
  "options": {
    "scales": {
      "yAxes": [{
        "ticks": {
          "beginAtZero": true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.min.js"></script>

<body>
  <canvas id="chartjs-7" class="chartjs" width="770" height="385" style="display: block; width: 770px; height: 385px;"></canvas>
</body>

However mine currently appears like this.

Stacked2

Any ideas how to do this or if it is even possible with graphJS I can't seem to find a way to stack these against each other

Upvotes: 0

Views: 473

Answers (1)

Fraction
Fraction

Reputation: 12974

You must add stacked: true to xAxes:

"options": {
    "scales": {
      "xAxes": [{
        "stacked": true,
      }],
      "yAxes": [{
        "ticks": {
          "beginAtZero": true
        }
      }]
    }
  }

Demo:

new Chart(document.getElementById("chartjs-7"), {
  "type": "bar",
  "data": {
    "labels": ["Petrol", "Food", "Kids Clubs", "Alcohol"],
    "datasets": [{
      "label": "Actual Spend",
      "data": [70, 100, 20, 29],
      "borderColor": "rgb(63, 191, 63)",
      "backgroundColor": "rgba(63, 191, 63)"
    }, {
      "label": "Budgeted amount",
      "data": [60, 150, 20, 30],
      "type": "bar",
      "fill": false,
      "borderColor": "rgb(63, 65, 191)",
      "backgroundColor": "rgba(63, 65, 191)"
    }]
  },
  "options": {
    "scales": {
      "xAxes": [{
        "stacked": true,
      }],
      "yAxes": [{
        //"stacked": true,
        "ticks": {
          "beginAtZero": true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.min.js"></script>

<body>
  <canvas id="chartjs-7" class="chartjs" width="770" height="385" style="display: block; width: 770px; height: 385px;"></canvas>
</body>

Upvotes: 1

Related Questions