Ask Your Question
4

How can a custom label with both amount and percentage be created using Chart.js and React?

asked 2023-06-29 16:44:19 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-06-29 17:13:02 +0000

huitzilopochtli gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-29 16:44:19 +0000

Seen: 8 times

Last updated: Jun 29 '23