1👍
✅
You can use the Plugin Core API. It offers different hooks that may be used for executing custom code. In below code snippet, I use the afterDraw
hook to draw a title on the canvas. That way you can draw as many titles as you want, define them of different style each and place them wherever it suits you.
Please note that inside chart options
, I also defined some layout padding. This prevents the title from overlapping the chart bars.
layout: {
padding: {
top: 40
}
}
Chart.plugins.register({
afterDraw: chart => {
var ctx = chart.chart.ctx;
ctx.save();
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.font = "18px Arial";
ctx.fillStyle = "gray";
ctx.fillText('Top Title', chart.chart.width / 2, 20);
ctx.restore();
}
});
new Chart(document.getElementById('myChart'), {
type: 'bar',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [{
data: [10, 12, 8, 6],
backgroundColor: ['red', 'blue', 'green', 'orange']
}]
},
options: {
layout: {
padding: {
top: 40
}
},
title: {
display: true,
text: 'Custom Chart Title',
position: 'bottom',
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="100"></canvas>
Source:stackexchange.com