Search code examples
javascriptjsoncanvasjs

Dynamic stacked column in CanvasJS


How can I create a stacked column chart with dynamic data?

For example, I have an external JSON object like:

[
  {
    id : ‘ID123’,
    occurrences: [5,6,8],
    description: ["Hours spent working", "Hours spent skiing", "Hours spent studying"]
  },
  {
    id : ‘ID456’,
    occurrences: [7,2,12],
    description: ["Hours spent working", "Hours spent skiing", "Hours spent studying"]
  }
]

How do I make it so there would be two stacked columns using the id as the label and the array of occurrences is used to build the stacked column on top of each label?

Edit: Added representation of how graph should look

Representation of graph


Solution

  • I would suggest using chart.js for this as it will be much easier than building it out yourself. Here is a example using the data you provided.

    var barChartData = {
    			labels: ['ID123', 'ID456'],
    			datasets: [{
    				label: 'Hours spent working',
    				backgroundColor: '#FF0000',
    				data: [
    					5,
    					7
    				]
    			}, {
    				label: 'Hours spent skiing',
    				backgroundColor: '#00FF00',
    				data: [
    					6,
    					2
    				]
    			}, {
    				label: 'Hours spent studying',
    				backgroundColor: '#0000FF',
    				data: [
    					8,
    					12,
    				]
    			}]
    
    		};
    		window.onload = function() {
    			var ctx = document.getElementById('canvas').getContext('2d');
    			window.myBar = new Chart(ctx, {
    				type: 'bar',
    				data: barChartData,
    				options: {
    					title: {
    						display: true,
    						text: 'Chart.js Bar Chart - Stacked'
    					},
    					tooltips: {
    						mode: 'index',
    						intersect: false
    					},
    					responsive: true,
    					scales: {
    						xAxes: [{
    							stacked: true,
    						}],
    						yAxes: [{
    							stacked: true
    						}]
    					}
    				}
    			});
    		};
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
    <canvas id="canvas"></canvas>