I want to change data label text to icon or image.
This chart show labels with months. I want to change this label text to icon or image
I want to change data label text to icon or image.
This chart show labels with months. I want to change this label text to icon or image
The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the afterDraw
hook to draw images instead of tick labels directly on the canvas using CanvasRenderingContext2D
.
You'll also have to instruct Chart.js not to display the default tick labels. This can be done through the following definition inside the chart options.
scales: {
xAxes: [{
ticks: {
display: false
}
}],
Further you need to define some padding at the bottom and right of the chart, otherwise you'll see only part of the images.
layout: {
padding: {
bottom: 30,
right: 15
}
},
Please have a look at the runnable code snippet below.
const labels = ['2020-02-06', '2020-02-07', '2020-02-08', '2020-02-09'];
const images = ['https://i.sstatic.net/2RAv2.png', 'https://i.sstatic.net/Tq5DA.png', 'https://i.sstatic.net/3KRtW.png', 'https://i.sstatic.net/iLyVi.png'];
const values = [48, 56, 33, 44];
new Chart(document.getElementById("myChart"), {
type: "line",
plugins: [{
afterDraw: chart => {
var ctx = chart.chart.ctx;
var xAxis = chart.scales['x-axis-0'];
var yAxis = chart.scales['y-axis-0'];
xAxis.ticks.forEach((value, index) => {
var x = xAxis.getPixelForTick(index);
var image = new Image();
image.src = images[index],
ctx.drawImage(image, x - 12, yAxis.bottom + 10);
});
}
}],
data: {
labels: labels,
datasets: [{
label: 'My Dataset',
data: values,
fill: false,
backgroundColor: 'green',
borderColor: 'green'
}]
},
options: {
responsive: true,
layout: {
padding: {
bottom: 30,
right: 15
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 20
}
}],
xAxes: [{
type: 'time',
time: {
unit: 'day',
tooltipFormat: 'MMM DD'
},
ticks: {
display: false
}
}],
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="90"></canvas>
© 2022 - 2024 — McMap. All rights reserved.