在react中使用chartjs显示值或百分比

问题描述 投票:0回答:2

我正在使用 ChartJS 在 React 项目中创建饼图。但我无法在不同的部分显示任何值。我尝试了不同的插件,但所有插件都不再受支持。

我对任何想法持开放态度。这就是我现在渲染图表的方式:

<Pie
  data={chartData}
  options={{
    responsive: true,
    plugins: {
        legend: {
            labels: {
                color: "white",
                font : {
                size: 16
            },
        }
      }
      },
    }}
/>
reactjs chart.js react-chartjs
2个回答
0
投票

您可以通过如下安装来使用 datalabels 插件的测试版:

YARN:
yarn add chartjs-plugin-datalabels@next

NPM:
npm i chartjs-plugin-datalabels@next

chart.js v3 的实时示例:

Chart.register(ChartDataLabels);

var options = {
  type: 'pie',
  data: {
    labels: ['orange', 'blue', 'gray'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
      borderWidth: 1,
      backgroundColor: ['orange', 'blue', 'gray']
    }]
  },
  options: {
    plugins: {
      datalabels: {
        backgroundColor: function(context) {
          return context.dataset.backgroundColor;
        },
        borderColor: 'white',
        borderRadius: 25,
        borderWidth: 3,
        color: 'white',
        font: {
          weight: 'bold'
        },
        padding: 6,


      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.3.2/chart.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
</body>


0
投票

LeeLenalee 给您的想法是正确的,但您需要对其进行一些调整以使其适应您的 React 实现。您仍然需要 chartjs-plugin-datalabels 库,但您需要在图表基础对象中注册此插件。

所以,总结一下:

  1. 您需要安装三个库

    npm install --save chart.js react-chartjs-2 chartjs-plugin-datalabels
    如果您还没有的话

  2. 在您要实施图表的位置导入以下内容

import { Chart } from 'chart.js';
import ChartDataLables from 'chartjs-plugin-datalabels';
import { Pie } from 'react-chartjs-2';
  1. 手动注册插件。这是让标签发挥作用的关键:
    Chart.register(ChartDataLables);
  2. 现在您可以将数据标签配置添加到插件道具中,这将显示图表内的值
datalabels: {
  display: true,
},

完成这些步骤后,您的饼图实现应该与此类似。我将它包装到一个新组件中,以便能够在需要时重用它。

import { Chart } from 'chart.js';
import ChartDataLables from 'chartjs-plugin-datalabels';
import { Pie } from 'react-chartjs-2';

Chart.register(ChartDataLables);

export const UsagePieChart = ({ chartData }) => {
  return (
    <Pie
      data={chartData}
      options={{
        responsive: true,
        maintainAspectRatio: true,
        plugins: {
          legend: {
            labels: {
              color: 'white',
              font: {
                size: 16,
              },
            },
          },
          datalabels: {
            display: true,
            color: 'white',
            font: {
              weight: 'bold',
            },
          },
        },
      }}
    />
  );
};

© www.soinside.com 2019 - 2024. All rights reserved.