Stacked Bars in Chart

Can you add a stacked option for the bar charts? The data items would need a stack property to group the data items.

Another topic was requesting info on this:

Thanks for the consideration

You can try this if you want stacked bars

HTML markup

add an attribute to the chart divs you want to be stacked

<div data-stacked>
	<canvas><canvas>
<div>

Javascript

document.addEventListener('DOMContentLoaded', function() {

	let stackedBars = document.querySelectorAll('[data-stacked] canvas');
	stackedBars.forEach(stackedBar => {
		stackedBar.chart.options.scales = {
			xAxes: [{
				stacked: true
			}],
			yAxes: [{
				stacked: true
			}]
		};
		stackedBar.chart.update()
	})
	

}, false);

BSS use the chartjs version 2.8. Don’t read the latest chartjs docs read the 2.8 docs

I’ve tried a few ways to make this work and am still struggling. I want to have three data sets along the X axis - two are stacked and one is not.

I think the solution is to have two data sets with the same stack property and the third with a different value. I think if the data sets in BSS would have this stack property and also indicate that the chart is stacked, it would work well.

You can’t do that with the chart widget in BSS. To stack individual dataset came in version 2.9.
You can do it custom code and javascript
like this

but then you can’t use the chart widget in BSS
This is the code in the example

linked exernal js
https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js

custom code

<canvas id="stackedStrawberries"></canvas>

javascript

document.addEventListener('DOMContentLoaded', function() {

	let stackedbarChartData = {
		labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
		datasets: [{
			label: 'Stacked 1',
			backgroundColor: '#20c997',
			stack: 'Stack 0',
			data: [
				1520,
				8547,
				8530,
				1477,
				5267,
				4587,
				4758
			]
		}, {
			label: 'Stacked 2',
			backgroundColor: '#ffc107',
			stack: 'Stack 0',
			data: [
				1500,
				1922,
				4722,
				4711,
				1020,
				1477,
				5000
			]
		}, {
			label: 'Not Stacked',
			backgroundColor: '#0d6efd',
			stack: 'Stack 1',
			data: [
				7800,
				1400,
				5620,
				1477,
				2010,
				7000,
				2000
			]
		}]
	};

	new Chart(document.getElementById('stackedStrawberries'), {
		type: 'bar',
		data: stackedbarChartData,
		options: {
			title: {
				display: true,
				text: 'Stacked strawberries',
				fontSize: 25
			},
			tooltips: {
				mode: 'index',
				intersect: false
			},
			responsive: true,
			scales: {
				xAxes: [{
					scaleLabel: {
						display: true,
						labelString: 'Year 2022'
					},
					stacked: true
				}],
				yAxes: [{
					scaleLabel: {
						display: true,
						labelString: 'Strawberries'
					},
					stacked: true
				}]
			}
		}
	});

}, false);

Thanks very much for your explanation

Stacked Bars is now in BSS starting with version 5.9.2 - thanks, works well.

1 Like