как отобразить значение в условных обозначениях круговой диаграммы в react-chartjs-2

#javascript #reactjs #react-chartjs-2

#javascript #reactjs #react-chartjs-2

Вопрос:

Я использую круговую диаграмму react-Chartjs-2 для своей панели мониторинга. в соответствии с требованием я должен показать обе метки с данными в легенде. приведенный ниже компонент, который я использую в своем приложении

 
import React, { Component } from "react";
import { Doughnut } from "react-chartjs-2";

class DoughnutChart extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    const chartdata = {
      labels: ["Newly Added", "Edited", "Deleted"],
      datasets: [
        {
          label: "Markets Monitored",
          backgroundColor: [
            "#83ce83",
            "#959595",
            "#f96a5d",
            "#00A6B4",
            "#6800B4",
          ],
          data: [9, 5, 3],
        },
      ],
    };
    return (
      <Doughnut
        data={chartdata}
        options={{
          legend: { display: true, position: "right" },

          datalabels: {
            display: true,
            color: "white",
          },
          tooltips: {
            backgroundColor: "#5a6e7f",
          },
        }}
      />
    );
  }
}

export default DoughnutChart;
 

теперь я получаю диаграмму, подобную приведенной ниже

, мое требование — добавление значений в легенду (настройка легенды диаграммы). пример ожидаемого результата изображения

Ответ №1:

Один из способов сделать это — определить данные и метки перед созданием диаграммы. Затем вы можете добавить данные в метки, используя метод .map.

 import React, { Component } from "react";
import { Doughnut } from "react-chartjs-2";

class DoughnutChart extends Component {
  constructor(props) {
    super(props);
  }

  render() {

    let data = [9, 5, 3]
    let labels = ["Newly Added", "Edited", "Deleted"]
    
    let customLabels = labels.map((label,index) =>`${label}: ${data[index]}`)

    const chartdata = {
      labels: customLabels,
      datasets: [
        {
          label: "Markets Monitored",
          backgroundColor: [
            "#83ce83",
            "#959595",
            "#f96a5d",
            "#00A6B4",
            "#6800B4",
          ],
          data: data,
        },
      ],
    };
    return (
      <Doughnut
        data={chartdata}
        options={{
          legend: { display: true, position: "right" },

          datalabels: {
            display: true,
            color: "white",
          },
          tooltips: {
            backgroundColor: "#5a6e7f",
          },
        }}
      />
    );
  }
}

export default DoughnutChart;