【避坑指“难”】React配置AntV G2 饼图

效果如下:
在这里插入图片描述
核心代码:

import { Chart } from '@antv/g2';
import React, { useEffect, useState } from 'react';

interface PieProps {
  dataList: any;
}
const Pie: React.FC<PieProps> = (props: any) => {
  const { dataList } = props;
  const data = dataList;
  const initial = () => {
    const chart = new Chart({
      container: 'container',
      autoFit: true,
      height: 100,
    });
    const innerView = chart.createView();
    chart.coordinate('theta', {
      radius: 0.75,
      innerRadius: 0.5,
    });
    chart.data(data);
    chart.scale('percent', {
      formatter: (val) => {
        val = val * 100 + '%';
        return val;
      },
    });

    chart.tooltip(false);
    // 声明需要进行自定义图例字段: 'item'
    chart.legend('item', {
    //   layout: 'horizontal',
      position: 'right', // 配置图例显示位置
      custom: true, // 关键字段,告诉 G2,要使用自定义的图例
      offsetX: -75,
      flipPage:false,
      maxWidthRatio:0.4,
      max: 20,
      items: data.map((obj, index) => {
        return {
          name: obj.item, // 对应 itemName
          value: obj.percent, // 对应 itemValue
          marker: {
            symbol: 'square', // marker 的形状
            style: {
              r: 5, // marker 图形半径
              fill: chart.getTheme().colors10[index], // marker 颜色,使用默认颜色,同图形对应
            },
          }, // marker 配置
        };
      }),
      itemValue: {
        style: {
          fill: '#999',
        }, // 配置 itemValue 样式
        formatter: (val) => `${val * 100}%`, // 格式化 itemValue 内容
      },
    });
    chart.scale('value', { nice: true });

    chart
      .interval()
      .adjust('stack')
      .position('percent')
      .color('item')
      .style({
        fillOpacity: 1,
      })
      .state({
        active: {
          style: (element) => {
            const shape = element.shape;
            return {
              lineWidth: 10,
              stroke: shape.attr('fill'),
              strokeOpacity: shape.attr('fillOpacity'),
            };
          },
        },
      });
    // 移除图例点击过滤交互
    chart.removeInteraction('legend-filter');
    chart.interaction('element-active');

    chart.render();
    // 监听 element 上状态的变化来动态更新 Annotation 信息
    // 监听 element 上状态的变化来动态更新 Annotation 信息
    chart.on('element:statechange', (ev) => {
      const { state, stateStatus, element } = ev.gEvent.originalEvent;

      // 本示例只需要监听 active 的状态变化
      if (state === 'active') {
        const data = element.getData();
        if (stateStatus) {
          // 更新 Annotation
          updateAnnotation(data);
        } else {
          // 隐藏 Annotation
          clearAnnotation();
        }
      }
    });

    // 绘制 annotation
    let lastItem;
    function updateAnnotation(data) {
      if (data.item !== lastItem) {
        innerView.annotation().clear(true);
        innerView
          .annotation()
          .text({
            position: ['50%', '50%'],
            content: data.item,
            style: {
              fontSize: 12,
              fill: '#333',
              textAlign: 'center',
            },
            offsetY: -5,
          })
          .text({
            position: ['50%', '50%'],
            content: data.count,
            style: {
              fontSize: 12,
              fill: '#333',
              textAlign: 'center',
            },
            // offsetX: -10,
            offsetY: 8,
          })
          .text({
            position: ['50%', '50%'],
            content: '',
            style: {
              fontSize: 20,
              fill: '#8c8c8c',
              textAlign: 'center',
            },
            offsetY: 20,
            offsetX: 20,
          });
        innerView.render(true);
        lastItem = data.item;
      }
    }

    // 清空 annotation
    function clearAnnotation() {
      innerView.annotation().clear(true);
      innerView.render(true);
      lastItem = null;
    }
  };
  useEffect(() => {
    initial();
  }, []);
  return (
    <>
      <div id="container" style={{ width: 320, display: 'flex',marginLeft:150 }}/>
    </>
  )
};
export default Pie;

渲染的数据格式:

const dataList = [
    { item: '管制', count: 42, percent: 0.54 },
    { item: '可疑', count: 21, percent: 0.27 },
    { item: '关注', count: 17, percent: 0.22 },
    ];
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

椰卤工程师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值