Reputation: 1517
In chart js bar chart is it possible to have custom text exactly under each bar ? in below images the first one correct and second one is not.
You can check demo here demo
any help please?
Upvotes: 0
Views: 1269
Reputation: 26150
I don't exactly understand why you want to repeat the labels on the xAxes but 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 text directly on the canvas.
The plugin would be defined as follows:
const plugins = [{
afterDraw: chart => {
var ctx = chart.chart.ctx;
ctx.save();
var xAxis = chart.scales["x-axis-0"];
var yAxis = chart.scales["y-axis-0"];
xAxis.ticks.forEach((v, i) => {
var x = xAxis.getPixelForTick(i);
var value = chart.data.datasets[0].data[i];
ctx.textAlign = "center";
ctx.font = "18px Arial";
ctx.fillStyle = value < 0 ? "#fc3e78" : "#53b300";
ctx.fillText(value, x, yAxis.bottom + 80);
ctx.fillText(likeslabels[i][0], x, yAxis.bottom + 100);
});
ctx.restore();
}
}];
Then tell the Bar
element about the plugin to be used.
<Bar
ref={barRef}
data={likesdata}
plugins={plugins} // add this line
width={75}
height={20}
options={likesoptions}
/>
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.
const likesoptions = {
layout: {
padding: {
bottom: 60
}
},
Please have a look at your amended CodeSandbox.
Upvotes: 1