Reputation: 2197
I have a graph which made up of react-chartjs
. Right now it has a text label. What I want is to put an image in the place of label text. I tried to add an image in the label but instead of showing an image, it is showing the path of that image.
Graph Data State variable
graphData: {
labels: ['4 A.M', '5 A.M', '6 A.M', '7 A.M', '8 A.M', '9 A.M', '10 A.M', '11 A.M', '12 P.M', '1 P.M', '2 P.M', '3 P.M', '4 P.M', '5 P.M', '6 P.M', '7 P.M', '8 P.M', '9 P.M', '10 P.M', '11 P.M', '12 A.M', '1 A.M', '2 A.M', '3 A.M'],
datasets: [{
label: User, //User image is imported in this component
backgroundColor: "#69c9e0",
borderColor: '#69c9e0',
borderWidth: 2,
lineTension: 0.1,
fill: true,
data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
},
{
label: User, //User image is imported in the label
backgroundColor: "#f8a046",
borderColor: '#f8a046',
borderWidth: 2,
lineTension: 0.1,
fill: true,
data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
}
]
}
Upvotes: 0
Views: 1990
Reputation: 26150
This can be done with the Plugin Core API. The API offers different hooks that may be used for executing custom code. In your case, you can use the afterDraw
hook to draw images (icons) instead of tick labels directly on the canvas using CanvasRenderingContext2D
.
The plugin would be defined as follows:
const plugins = [{
afterDraw: chart => {
let ctx = chart.chart.ctx;
ctx.save();
let xAxis = chart.scales['x-axis-0'];
let yAxis = chart.scales['y-axis-0'];
xAxis.ticks.forEach((value, index) => {
let x = xAxis.getPixelForTick(index);
let image = new Image();
image.src = ..., // provide the image URL
ctx.drawImage(image, x - 12, yAxis.bottom + 10);
});
ctx.restore();
}];
Then tell the Bar
element about the plugin
to be used.
<Bar
...
plugins={plugins}
/>
Also add some extra space at the bottom of the chart by defining layout.padding.bottom
inside the chart options
, otherwise the text won't be visible.
layout: {
padding: {
bottom: 60
}
},
Upvotes: 1