Skip to content

Data Labels

Example of a bar chart with the value of each bar above it, made with the <Bar> component and chartjs-plugin-datalabels, a plugin that draws labels on the elements of a Chart.js chart. Install it next to Chart.js:

Terminal window
pnpm add chartjs-plugin-datalabels

The plugin does not register itself, so a chart shows no labels until it gets the plugin: the example passes it to its chart with the plugins prop. ChartJS.register(ChartDataLabels) gives the plugin to every chart instead, and then display: false in options.plugins.datalabels hides the labels of a chart. To show and hide the labels of a chart that is already on the page, change display too: a new plugins array does not change an existing chart, as Why doesn't the chart use new plugins? explains. See registration in the plugin documentation.

The labels take their options from options.plugins.datalabels, and a dataset can override them in its own datalabels property. Without options, a label sits in the middle of its bar. Here anchor: 'end' and align: 'end' put it above the bar, formatter turns the value into the text of the label, and grace: '10%' on the y scale leaves room for the label of the highest bar. On a pie chart or a doughnut chart, the labels take the same options and sit in the middle of the slices by default. See positioning and formatting in the plugin documentation.

Importing the plugin also adds its options to the types of Chart.js, so TypeScript checks the datalabels options of charts and datasets. A plugin of your own needs such types as well, see Options of a custom plugin.

App.tsx
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip
} from 'chart.js'
import ChartDataLabels from 'chartjs-plugin-datalabels'
import { Bar } from 'react-chartjs-2'
import { faker } from '@faker-js/faker'
ChartJS.register(
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip
)
export const options = {
responsive: true,
plugins: {
title: {
display: true,
text: 'Chart.js Bar Chart with Data Labels'
},
datalabels: {
anchor: 'end' as const,
align: 'end' as const,
formatter: (value: number) => `$${value}`
}
},
scales: {
y: {
// Room above the highest bar for its label
grace: '10%'
}
}
}
const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July']
export const data = {
labels,
datasets: [
{
label: 'Sales',
data: labels.map(() => faker.number.int({
min: 0,
max: 1000
})),
backgroundColor: 'rgba(53, 162, 235, 0.5)'
}
]
}
export function App() {
return (
<Bar
options={options}
data={data}
plugins={[ChartDataLabels]}
/>
)
}