ChartJS 访问React图的切片饼图

acruukt9  于 2022-11-06  发布在  Chart.js
关注(0)|答案(2)|浏览(229)

我正在尝试使用react-chartjs-2创建一个静态(不可单击)饼图。
然而,我希望其中一个切片“弹出”,或者看起来比其他的更大:

因此,我尝试访问饼图中的一个扇区,并修改其outerRadius属性。

我在Stack OverflowGithub中都遇到了多个类似的问题,这些问题帮助我得出了以下结论:

  1. import { Pie } from 'react-chartjs-2';
  2. <Pie
  3. data={data}
  4. options={options}
  5. getElementsAtEvent={(elems) => {
  6. // Modify the size of the clicked slice
  7. elems[0]['_model'].outerRadius = 100;
  8. }}
  9. />

然而,我没有发现任何关于让一个切片弹出没有用户点击它。

hfsqlsce

hfsqlsce1#

在深入研究Pie组件的引擎盖之后,我最终找到了答案。
您可以在componentDidMount()中找到它:

  1. import React, { Component } from 'react';
  2. import { Pie } from 'react-chartjs-2';
  3. class PieChart extends Component {
  4. componentDidMount() {
  5. const change = {
  6. sliceIndex: 0,
  7. newOuterRadius: 100
  8. }
  9. const meta = this.pie.props.data.datasets[0]._meta;
  10. meta[Object.keys(meta)[0]]
  11. .data[change.sliceIndex]
  12. ._model
  13. .outerRadius = change.newOuterRadius;
  14. }
  15. render() {
  16. const data = {
  17. type: 'pie',
  18. datasets: [ { data: [10, 20, 30] } ],
  19. labels: ['a', 'b', 'c'],
  20. };
  21. const options = {};
  22. return <Pie
  23. ref={(self) => this.pie = self}
  24. data={data}
  25. options={options}
  26. />
  27. }
  28. }
  29. export default PieChart;
展开查看全部
rjee0c15

rjee0c152#

我还有一个版本4.3.1的解决方案。尝试将offset属性添加到数据集中。

  1. import { Pie } from 'react-chartjs-2';
  2. <Pie
  3. data={
  4. datasets: [
  5. {
  6. data: [1, 1],
  7. borderColor: ['black', 'transparent'],
  8. offset: [10, 0],
  9. },
  10. ],
  11. }
  12. />

它将呈现具有2个部分的饼图。对于第一个部分,您将具有 * 黑色 * 边框和10px偏移量

相关问题