Given the following chart how can I show a custom HTML label for the Y ticks?
const yAxisLabelsLookup = {
0: {
label: '2024-01-01',
color: 'red',
},
1: {
label: '2024-01-02',
color: 'blue',
},
2: {
label: '2024-01-03',
color: 'green',
},
3: {
label: '2024-01-04',
color: 'yellow',
},
}
const ctx = document.getElementById('chart-container');
const data = {
datasets: [{
label: 'First Dataset',
data: [
{
x: 20,
y: 0,
r: 15
}, {
x: 40,
y: 0,
r: 10
},
{
x: 20,
y: 1,
r: 10
},
{
x: 40,
y: 1,
r: 10
},
{
x: 25,
y: 2,
r: 10
},
{
x: 35,
y: 2,
r: 10
},
],
backgroundColor: 'rgb(255, 99, 132)'
}]
};
const chart = new Chart(ctx, {
type: 'bubble',
data: data,
options: {
// So we can set the height with css.
// maintainAspectRatio: false,
responsive: true,
scales: {
x: {
type: 'time',
// time: {
// displayFormats: {
// quarter: 'MMM YYYY'
// }
// }
position: 'top',
ticks: {
padding: 15,
},
},
y: {
// display: false,
ticks: {
padding: 25,
callback: function (value) {
if (value in yAxisLabelsLookup) {
const label = yAxisLabelsLookup[value].label;
const color = yAxisLabelsLookup[value].color;
return `<span style="color: ${color};">${label}</span>`;
} else {
// Return the default numeric value if no custom label is found
return value;
}
// if (value in dateLookupMap) {
// return dateLookupMap[value]
// } else {
// return ''
// }
}
}
},
}
}
});
2
Answers
chart.js
uses canvas to render charts; you can’t return html to format stuff inside the chart.All available options
are to be set through the configuration object.
Some options are scriptable,
which means that the value can be a function, that will be called only when the option is needed and
should return the actual value of the option based on the context, in a similar way to what
callback
does fortick labels text.
The tick label color can be set through
options.scales.y.ticks.color
, programmatically if needed since it isscriptable. Similarly, you may use
options.scales.y.ticks.font
to set other visual properties of labels like size or weight.Your code could thus be changed to:
Snippet:
I added just one example about the customizing label of the chart. I added one link, you can follow.
https://www.chartjs.org/docs/latest/samples/scale-options/ticks.html