图表Piechart在悬停时只显示百分比,但它显示数据和百分比标签,我只想显示百分比

cgh8pdjw  于 2023-02-04  发布在  Chart.js
关注(0)|答案(1)|浏览(140)
import React from "react";
import { Pie } from "react-chartjs-2";

function Test() {
  const data2 = [20, 10, 8, 10, 30, 3, 1, 12, 5, 2, 1, 2];

  //method 2

  const names = [
    "Burn/ Charity",
    "for sale",
    "Liquidity",
    "Team",
    "Locked",
    "Released/mo",
    "charity",
    "Marketing/Sales",
    "Tax on Sales",
    "Charity",
    "Liquidity",
    "to Tokes Holder",
  ];

  let total = data2.reduce(
    (accumulator, currentValue) => accumulator + currentValue
  );
  console.log(total);

  let labelss = data2.map(
    (value, index) => Math.round((value / total) * 100) + "%"
  );
  const data4 = data2.map((item, index) => {
    return names[index] + " " + labelss[index];
  });

  const data = {
    labels: data4,
    datasets: [
      {
        data: data2,

        backgroundColor: [
          "red",
          "yellow",
          "blue",
          "black",
          "orange",
          "grey",
          "green",
          "salmon",
          "grey",
          "lightgreen",
          "pink",
          "yellow",
        ],
      },
    ],
  };

  return <Pie data={data} />;
}

export default Test;
rjjhvcjd

rjjhvcjd1#

您可以使用工具提示label回调,如下所示:

function Test() {
  const data2 = [20, 10, 8, 10, 30, 3, 1, 12, 5, 2, 1, 2];

  //method 2

  const names = [
    "Burn/ Charity",
    "for sale",
    "Liquidity",
    "Team",
    "Locked",
    "Released/mo",
    "charity",
    "Marketing/Sales",
    "Tax on Sales",
    "Charity",
    "Liquidity",
    "to Tokes Holder",
  ];

  let total = data2.reduce(
    (accumulator, currentValue) => accumulator + currentValue
  );
  console.log(total);

  let labelss = data2.map(
    (value, index) => Math.round((value / total) * 100) + "%"
  );
  const data4 = data2.map((item, index) => {
    return names[index] + " " + labelss[index];
  });

  const data = {
    labels: data4,
    datasets: [{
      data: data2,

      backgroundColor: [
        "red",
        "yellow",
        "blue",
        "black",
        "orange",
        "grey",
        "green",
        "salmon",
        "grey",
        "lightgreen",
        "pink",
        "yellow",
      ],
    }, ],
  };

  const ctx = document.getElementById('chartJSContainer').getContext('2d');
  new Chart(ctx, {
    type: 'doughnut',
    data: data,
    options: {
      plugins: {
        tooltip: {
          callbacks: {
            label: (ttItem) => (ttItem.label)
          }
        }
      }
    }
  });
}

Test();
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.0/chart.js"></script>
</body>

如果我没记错的话,对于react包,你需要在prop变量中提供选项,就像你对data所做的那样,所以你会得到这样的结果:

const opts = {
    plugins: {
        tooltip: {
          callbacks: {
            label: (ttItem) => (ttItem.label)
        }
      }
    }
  };

return <Pie data={data} options={opts}/>;

相关问题