To display the chart data labels using the “center” option in Chart.js, you can use the chartjs-plugin-datalabels
plugin. This plugin allows you to customize the placement of data labels on your chart. Below are the steps and code needed to achieve this:
Include the necessary libraries: Make sure to include Chart.js and the Chart.js Data Labels plugin in your HTML file.
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
Create the chart: Set up your chart configuration to use the Data Labels plugin and specify the align
option as center
.
<canvas id="myChart"></canvas>
<script>
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar', // You can change this to the type of chart you are using
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June'],
datasets: [{
label: 'My Dataset',
data: [65, 59, 80, 81, 56, 55],
backgroundColor: 'rgba(75, 192, 192, 0.2)',
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 1
}]
},
options: {
plugins: {
datalabels: {
align: 'center',
anchor: 'center'
}
},
scales: {
y: {
beginAtZero: true
}
}
}
});
</script>
In this example:
type
: Specifies the type of chart (e.g.,bar
,line
, etc.).data
: Contains the dataset and labels for your chart.options
: Holds various configuration options for the chart.plugins
: This is where you configure thechartjs-plugin-datalabels
.datalabels
: Settings for the Data Labels plugin.align
: Sets the alignment of the data labels.center
will place the label in the center of the element (bar, point, etc.).anchor
: Determines the position of the label relative to the element.center
will position the label at the center of the element.
Customization: You can further customize the appearance and behavior of the data labels using other options provided by the plugin, such as color
, font
, formatter
, and more.
Here is an example with additional customization:
options: {
plugins: {
datalabels: {
align: 'center',
anchor: 'center',
color: '#000000',
font: {
weight: 'bold',
size: 14
},
formatter: (value, context) => {
return value + '%'; // Example: append a percentage sign to the value
}
}
},
scales: {
y: {
beginAtZero: true
}
}
}
With these settings, the data labels will be centered within each element on your chart, providing a clear and neat presentation of the data values.