Open1

chart.jsでstackされた棒グラフの集計値を表示する

yunayuna

要件:stackされた棒グラフの上部に、その合計値を表示したい

stacked bar graphの表示方法

サンプルを元に、scalesのx,y軸共にstacked: trueを指定すればOK。

scales: {
				y: {
					stacked: true,
				},
				x: {
					stacked: true,

https://www.chartjs.org/docs/latest/samples/bar/stacked.html

合計値を表示する方法

chartjs-plugin-datalabels を利用します。(更新止まってますが、chart.js v4.xでも利用可能)
https://github.com/chartjs/chartjs-plugin-datalabels

最低限の設定で使うと、

import ChartDataLabels from 'chartjs-plugin-datalabels';
...
ChartJS.register(
  ChartDataLabels,
);
...
plugins: [ChartDataLabels],

各内訳に数値が表示されてしまう。

なので、一工夫が必要。
表示ロジックをfunctionで指定できるので、
1.各値の集計を表示するようにする
2.グラフの最後(最上部)のみ、表示するようにする

と指定することで、要件に対応できました。

plugins: {
			datalabels: {
					anchor: 'end',
					align: 'end',
					formatter: (value, context) => {
						const datasetIndex = context.datasetIndex;
						const datasetLength = context.chart.data.datasets.length;

						// 最後のデータセットの場合にのみ合計値を返す
						if (datasetIndex === datasetLength - 1) {
							// 各棒(グループ)の合計値を計算
							const total = context.chart.data.datasets.reduce((sum, dataset) => {
								return sum + dataset.data[context.dataIndex] || 0;
							}, 0);
							// 合計値を返す
							return total;
						}
						// 最後のデータ項目でない場合は空文字を返す
						return '';
					},
					color: 'black',
				}
			},