I can display data values on react-chartjs-2 !! I register a plugin (using for all chart) and custom code plugin and data for chart
Chart.plugins.register({
id: "datalabels",
afterDatasetsDraw: (chart, easing) => {
if (!chart.data.showLabel) return null;
const ctx = chart.ctx;
chart.data.datasets.forEach((dataset, i) => {
if (!chart.data || !chart.data.typeShow[dataset.type]) return;
const meta = chart.getDatasetMeta(i);
if (!meta.hidden) {
meta.data.forEach((element, index) => {
ctx.fillStyle = "rgb(0, 0, 0)";
const fontSize = 16;
const fontStyle = "normal";
const fontFamily = "Helvetica Neue";
ctx.font = Chart.helpers.fontString(
fontSize,
fontStyle,
fontFamily
);
const value = dataset.data[index];
let dataString = "";
if (typeof value === "object" && value) {
dataString = value.label ? value.label : "_";
} else {
dataString = value ? value : "_";
}
dataString = dataString.toString();
ctx.textAlign = "center";
ctx.textBaseline = "middle";
const padding = 5;
const position = element.tooltipPosition();
ctx.fillText(
dataString,
position.x,
position.y - fontSize / 2 - padding
);
});
}
});
}
});
DATA custom:
const chartBar = {
showLabel: true,
typeShow: { bar: true },
labels: labels,
datasets: [
{
label: "AAAA",
type: "line",
data: dataLine,
fill: false,
borderColor: "#EC932F",
backgroundColor: "#EC932F",
pointBorderColor: "#EC932F",
pointBackgroundColor: "#EC932F",
pointHoverBackgroundColor: "#EC932F",
pointHoverBorderColor: "#EC932F",
yAxisID: "y-axis-2"
},
{
type: "bar",
data: dataBar,
borderWidth: 1,
label: "BBBB ",
backgroundColor: "#71B37C",
borderColor: "#71B37C",
hoverBackgroundColor: "#71B37C",
hoverBorderColor: "#71B37C",
yAxisID: "y-axis-1"
}
]
};
I add two field "showLabel" and "typeShow" .
I think it's help you :)
For future reference, I used _chartjs-plugin-datalabels_ plugin. First I installed it using:
npm install chartjs-plugin-datalabels --save
Then I imported it in my React Component:
import "chartjs-plugin-datalabels";
For my case, I needed a Bubble graph with each bubble to display a different label (not the x nor y values), so I included the following in the options object:
plugins: {
datalabels: {
display: ctx => {
return true;
},
formatter: (ctx, data) => {
return `${data.dataIndex}`;
}
}
}
Most helpful comment
For future reference, I used _chartjs-plugin-datalabels_ plugin. First I installed it using:
Then I imported it in my React Component:
For my case, I needed a Bubble graph with each bubble to display a different label (not the x nor y values), so I included the following in the options object: