javascript
Add a title to the chart in Chart.js
To add a title on the top of the chart, the below code can be used. Chart.js uses the subtitle object to define your subtitle text and style them.
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr'],
datasets: [{
label: 'Month',
data: [10, 20, 50, 30]
}]
},
options: {
plugins: {
subtitle: {
display: true,
text: 'Title goes here ...',
color: '#ff0000',
font: {
size: 20
}
}
}
}
});
We can configure a chart created using Chart.js library using options object. It contains object plugins where we can define a subtitle object that will add a title that contains the text that is passed to its text property.
The code for adding the title to Chart.js
plugins: {
subtitle: {
display: true,
text: 'Title content will be here',
}
}
Live Demo for adding title
subtitle: {
display: true,
text: 'Title text',
color: '#ff0000',
}
To change the color of the subtitle you can assign a color property of the subtitle object. As the value of the color property, use color in hex format or RGBA format.
plugins: {
subtitle: {
display: true,
text: 'Title content will be here',
font: {
size: 22 // Change font size here
}
}
}
To change the font size of the subtitle, a font object can be used. we can assign size property to this font object and the value we assign to size is considered in px.
Was this helpful?
Similar Posts