1

enter image description here I want to add data label in the doughnut chart.I have attached a screenshot as i want the required the output.

2 Answers2

0

Best way to achieve that is to create a custom plugin and assign it to plugins prop.

Video here describes the process step-by-step.

const plugins = [{
    id: 'insideLabelsPlugin',
    afterDatasetsDraw(chart) {
        const {
            ctx,
            data: {
                datasets,
            },
            chartArea: {
                width, height,
            },
        } = chart;

        const chartData = chart.getDatasetMeta(0).data;

        chartData.forEach((datapoint, i) => {
            const { x, y } = datapoint.getCenterPoint();
            const value = datasets[1].data[i];
            const sumOfValues = datasets[1].data.reduce((acc, val) => acc + val);
            ctx.textBaseline = 'middle';

            const textX = x - (ctx.measureText(value).width / 2);

            if (value / sumOfValues > 0.05) {
                ctx.fillStyle = '#f4f6f7';
                ctx.fillText(datasets[1].data[i], textX, y);
            }
        });
    },
}];

Then, in your Component:

import {
    Chart as ChartJS, ArcElement, Tooltip,
} from 'chart.js';
import { Doughnut } from 'react-chartjs-2';
import plugins from './plugins';

ChartJS.register(ArcElement, Tooltip);

const Chart = ({
    data,
    options,
    plugins,
}) => (
        <Doughnut
            data={data}
            options={options}
            plugins={plugins}
        />
    );

export default Chart;
0

You can try the plugin.datalabels.formatter property. Try to adapt the following code to yours.

// Disclaimer this code is a guide.

import { Doughnut } from 'react-chartjs-2';

const renderCustomDoughnut = (customData) => (
    <Doughnut
        data={{
            labels: customData.map((d) => (d.name)),
            datasets: [
                {
                    data: customData.map((d) => (d.value))
                }
            ]
        }}
        options={{
            plugins: {
                datalabels: {
                    formatter: (value, context) => {
                        const dataIndex = context.dataIndex;
                        return context.chart.data.labels[dataIndex];
                    }
                }
            },
        }}
    />
);

const myData = [
    { name: 'One', value: 1 },
    { name: 'Two', value: 2 },
];

// --- In your JSX render 
return (
  <> 
    {renderCustomDoughnut(myData)}
  </>
);
eliastg
  • 449
  • 1
  • 4
  • 14