How to create stacked bar chart from json in chart.js?

by darrion.kuhn , in category: Javascript , 9 months ago

How to create stacked bar chart from json in chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elisha_langworth , 9 months ago

@darrion.kuhn 

To create a stacked bar chart from JSON using Chart.js, you need to parse the JSON data and then configure the chart options and data sets accordingly. Here are the steps:

  1. First, include the Chart.js library in your HTML document. You can download it from the official website or use a CDN.
1
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>


  1. Next, create a canvas element where the chart will be displayed.
1
<canvas id="myChart"></canvas>


  1. Parse your JSON data to retrieve the necessary values for the chart.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
var jsonData = {
  "labels": ["Label 1", "Label 2", "Label 3"],
  "datasets": [
    {
      "label": "Dataset 1",
      "data": [10, 20, 30],
      "backgroundColor": "#FF6384"
    },
    {
      "label": "Dataset 2",
      "data": [40, 50, 60],
      "backgroundColor": "#36A2EB"
    }
  ]
};


  1. Create the bar chart using the parsed JSON data.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
var ctx = document.getElementById('myChart').getContext('2d');

var chart = new Chart(ctx, {
  type: 'bar',
  data: jsonData,
  options: {
    scales: {
      x: {
        stacked: true
      },
      y: {
        stacked: true
      }
    }
  }
});


The above code assumes that the JSON data contains an array of labels and an array of datasets. Each dataset represents a stack. The data array inside each dataset represents the values for each label, and the backgroundColor property sets the color for each stack.


By setting the stacked property to true for both the x and y axes in the options object, the bars will be stacked vertically and horizontally.


You can customize further aspects of the chart, such as colors, labels, and tooltips, by referring to the Chart.js documentation.