I'm attempting to create a chart using Chart.js and I'm using the 4.4.1 version for creating a horizontal chart.
In my code, the data labels are currently displayed as "x: 222, y: 1" but I intend for them to show only the main value, which is "222".
I am using below script tag below:
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js" ></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0"></script>
Below is my code:
Chart.register(ChartDataLabels);
new Chart('myChart', {
type: 'bar',
plugins: [{
afterInit: chart => {
let dataset = chart.data.datasets[0];
chart.data.datasets = chart.data.labels.map((l, i) => ({
label: l,
data: [{ x: dataset.data[i], y: i }],
backgroundColor: dataset.backgroundColor[i],
categoryPercentage: 1
}));
chart.data.labels = undefined;
},
beforeLayout: chart => {
chart.options.scales.y1.labels = chart.data.datasets.filter((ds, i) => !chart.getDatasetMeta(i).hidden).map(ds => ds.label);
}
}],
data: {
labels: ['Red', 'Blue', 'Green', 'Teal', 'Yellow', 'Purple', 'Orange', 'Black'],
datasets: [{
data: [123, 321, 213, 111, 222, 333, 234, 444],
backgroundColor: ['Red', 'Blue', 'Green', 'Teal', 'Yellow', 'Purple', 'Orange', 'Black']
}]
},
options: {
indexAxis: 'y',
maintainAspectRatio: false,
plugins: {
datalabels: {
color: 'white',
},
legend: {
position: 'top'
},
tooltip: {
callbacks: {
title: () => null
}
}
},
scales: {
x: {
title: {
display: true,
text: 'xAxis'
}
},
y: {
display: false,
},
y1: {
title: {
display: true,
text: 'yAxisLabel'
},
offset: true
}
}
},
});
Output:
You can use the formatter
function to customize the displayed text for the data label.
In your case, you will show the x
as the displayed data label.
datalabels: {
...,
formatter: function (value, context) {
return value.x;
},