I have created an horizontal stacked bar chart using Chart.js and Chartjs-plugin-datalabel. Here are the options I defined for the chart :
{
indexAxis: "y",
animation: false,
aspectRatio: 0.2,
maintainAspectRatio: false,
scales: {
x: {
axis: "x",
},
y: {
axis: "y",
}
},
x: {
beginAtZero: true,
stacked: true
},
y: {
beginAtZero: true,
stacked: true
},
cutout: "50%",
plugins: {
title: {
color: "gray",
font: {
weight: "bold",
size: 12
}
},
legend: {
display: false,
position: "top"
},
datalabels: {
color: "white",
align: "center",
anchor: "center",
textAlign: "center",
formatter: (val: number, ctx: Context): string => {
if (val) {
const label = ctx.chart.data.labels[ctx.datasetIndex] as string;
const value = ctx.chart.data.datasets[ctx.datasetIndex].data[0];
return `${label} (${value})`;
}
return '';
},
},
tooltip: {
enabled: true,
callbacks: {
title: (): string => '',
label: (tooltipItem: any): string => {
const { chart } = tooltipItem;
const label = chart.data.labels[tooltipItem.datasetIndex];
const value: number = chart.data.datasets[tooltipItem.datasetIndex].data[0];
return `${label}: ${value}`;
},
},
},
},
}
Then I use theses options in the html template like this :
<p-chart type="bar" [data]="data" [plugins]="barChartPlugins"
[options]="options" width="280px" height="80px" />
(for those who wonder, I use Angular and Primeng)
I put everything to 'center' in the datalabels property. Here is the result :
I have tried to change the values of these properties, play with the offset, add padding top, but this does not enable me to move the labels in the center of the chart in a vertical axis (at the same level as the (23) on the right). They are always on the top and I cannot figure why.
How can I center them ?
PS : the result is not so bad here. It depends on the size of the chart, sometimes it is too small. Then the labels are too high and we cannot see the top of it. This is why I would like to center them.