0

I am trying to implement nested Doughnut using React-ChartJS-2 but the label seem not to appear correctly in the Outer Doughnut. Here is what I tried after checking out many examples online.

The version I use for chart.js is ^3.7.1 and ^4.1.0 for react-chartjs-2

import React from "react";
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from "chart.js";
import { Doughnut } from "react-chartjs-2";

ChartJS.register(ArcElement, Tooltip, Legend);

const DoughnutChart = ({ xLabels, yData, titleText }) => {
  console.log(xLabels);
  console.log(yData);

  const options = {
    responsive: true,
    rotation: 270,
    circumference: 180,
    maintainAspectRatio: true,
    animation: false,

    legend: {
      display: false,
    },

    plugins: {
      tooltips: {
        callbacks: {
          label: function (tooltipItem, data) {
            console.log(tooltipItem.datasetIndex);
            var dataset = data.datasets[tooltipItem.datasetIndex];
            var index = tooltipItem.index;

            return dataset.labels[index] + ": " + dataset.data[index];
          },
        },
      },
    },
  };

  const data = {
    labels: ["Time elapsed", "Time remaining"],
    datasets: [
      {
        labels: ["Total Time"],
        label: "D1",
        data: [5],
        backgroundColor: ["rgb(80, 170, 80)", "#ccc"],
      },
      {
        label: "D2",
        labels: ["Time elapsed", "Time remaining"],
        data: [3.2, 1.3],
        backgroundColor: ["goldenrod", "#cccff"],
      },
    ],
  };

  return (
    <div style={{ position: "relative", margin: "auto", width: "80%" }}>
      <Doughnut data={data} options={options} />
    </div>
  );
};

export default DoughnutChart;
  • The outer doughnut "1" label should be Time elapsed: 5 (does not show correct label)
  • The inner doughnut "2" label should be Time elapsed: 3.2 and "3" should be Time remaining: 1.3 (correct label is shown)

I expect the outer doughnut label to show Total Time: 5 but I see Time elapsed: 5. How do I fix it or what am I doing wrong ?

By the way, I try to use the call back to update the label but it seems not to work.

enter image description here

Tee
  • 385
  • 3
  • 14

1 Answers1

0

For those facing similar issue, to name individual doughnut chart based on separate data within the dataset, I updated the callbacks for the tooltip like so:

plugins: {
      tooltip: {
        enabled: true,
        callbacks: {
          label: (tooltipItem) => {
            var dataIndex = tooltipItem.dataIndex;
            return (tooltipItem.dataset.labels[dataIndex] + ": " + tooltipItem.dataset.data[dataIndex]
            );
          }
        }
      }
   }

Note: For Chart.js 3, "context" parameter can also be used instead of tooltipItem.

Tee
  • 385
  • 3
  • 14