1 | initial version |
To create a custom label with both amount and percentage using Chart.js and React, you can use the "tooltips" and "plugins" features of Chart.js. Here are the steps to follow:
Step 1: Add Chart.js and React-Chartjs-2 libraries to your React project
Step 2: Create a state variable called "chartData" that contains the data for your chart, including labels, values, and colors
const [chartData, setChartData] = useState({
labels: ["Label 1", "Label 2", "Label 3"],
datasets: [
{
label: "Dataset 1",
data: [10, 20, 30],
backgroundColor: ["#FF6384", "#36A2EB", "#FFCE56"]
}
]
});
Step 3: Define the options for your chart, including tooltips and a custom plugin that adds a label with both amount and percentage
const options = {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var dataset = data.datasets[tooltipItem.datasetIndex];
var total = dataset.data.reduce(function(previousValue, currentValue, currentIndex, array) {
return previousValue + currentValue;
});
var currentValue = dataset.data[tooltipItem.index];
var percentage = Math.floor(((currentValue / total) * 100) + 0.5);
return currentValue + ' (' + percentage + '%)';
}
}
},
plugins: {
labels: {
render: function(args) {
return args.value + ' (' + args.percentage + '%)';
},
precision: 0,
fontSize: 12,
fontColor: '#fff',
arc: true
}
}
};
Step 4: Render the chart using the React-Chartjs-2 component
<Line data={chartData} options={options} />
The above code creates a Line chart but you can replace it with the type of chart you wish to use. This will create a custom label that displays both the amount and percentage for each data point in the chart.