I have the following package installed to add labels to my charts -
import * as pluginDataLabels from "chartjs-plugin-labels";
It is working fine on my line charts, pie charts and normal bar charts. However, it isn't displaying anything on my stacked bar chart. Here is my code:
public stackedChartLabels = ["Test 1"];
public stackedChartPlugins = [pluginDataLabels];
public stackedChartData = [
{
label: "Low",
data: [67.8],
backgroundColor: "#D6E9C6", // green
stack: "a",
},
{
label: "Moderate",
data: [20.7],
backgroundColor: "#FAEBCC", // yellow
stack: "a",
},
{
label: "High",
data: [11.4],
backgroundColor: "#EBCCD1", // red
stack: "a",
},
];
public stackedChartOptions = {
responsive: true,
maintainAspectRatio: false,
plugins: {
labels: [
{
render: function (args) {
return args.value;
},
position: "inside",
fontColor: "#023d7d",
fontSize: 12,
},
],
},
scales: {
yAxes: [
{
ticks: {
fontSize: 12,
fontColor: "#023d7d",
},
},
],
xAxes: [
{
ticks: {
min: 0,
max: 100,
fontSize: 12,
fontColor: "#023d7d",
precision: 0,
},
},
],
},
};
Here is the html code:
<canvas
baseChart
[datasets]="stackedChartData"
[labels]="stackedChartLabels"
[chartType]="'horizontalBar'"
[legend]="false"
[plugins]="stackedChartPlugins"
[options]="stackedChartOptions"
height="150"
>
</canvas>
Does anyone know how i can get the labels to display? I want them to show the value on each segment.
The following code fixed this:
animation: {
duration: 1000,
onComplete() {
let chartInstance = this.chart;
let ctx = chartInstance.ctx;
ctx.textAlign = "end";
ctx.textBaseline = "middle";
ctx.fillStyle = "#fff";
ctx.font = "10px sans-serif";
this.data.datasets.forEach(function (dataset, i) {
var label = dataset.label;
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function (bar, index) {
var data = dataset.data[index];
if (label.indexOf("%") >= 0) data += "%";
ctx.fillText(data + "%", bar._model.x, bar._model.y);
});
});
},
},