【问题标题】:showing values or percentages with chartjs in react在 react 中使用 chartjs 显示值或百分比
【发布时间】:2021-06-07 15:09:56
【问题描述】:

我正在使用 chartjs 在 react 项目中创建饼图。但我无法在不同的细分市场上显示任何值。我尝试了不同的插件,但不再支持所有插件。

我愿意接受任何想法。这就是我现在渲染图表的方式:

<Pie
  data={chartData}
  options={{
    responsive: true,
    plugins: {
        legend: {
            labels: {
                color: "white",
                font : {
                size: 16
            },
        }
      }
      },
    }}
/>

【问题讨论】:

  • 为了更好地帮助你,最好知道你是在 react 中使用 chartjs,还是在使用 react-chartjs npm 包,或者类似的东西。
  • 我正在使用 npm 包 :)

标签: reactjs chart.js react-chartjs


【解决方案1】:

您可以像这样安装 datalabels 插件的 beta 版:

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/chartjs-plugin-datalabels@2.0.0-rc"></script>
</body>

【讨论】:

  • 我是新手。我曾尝试注册该插件,但未能成功。现在我只从“react-chartjs-2”导入。当我尝试从“chartjs”导入时,它说它没有默认导出。所以我无法正确注册插件。因此它不起作用。感谢您的帮助
  • 这里是缩放插件的反应示例,​​它向您展示了如何注册它,如果您以相同的方式进行注册,它将起作用:codesandbox.io/s/react-chart-js-forked-cn6wh?file=/src/…
  • 非常感谢!这有很大帮助。带我去长你:D
猜你喜欢
  • 2021-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多