본문 바로가기

react

react 그래프 라이브러리, antv g6.Graph 커스텀하기

 

G6 图可视化引擎

A collection of charts made with the Grammar of Graphics

g6.antv.vision

antv Graph란? 

antv는 ant design에서 제공하는 차트 라이브러리이다. 그 중 G6는 그래프 관련 라이브러리를 제공한다. 

 

Gallery

A collection of charts made with the Grammar of Graphics

g6.antv.vision

위 링크로 들어가면 다양한 종류의 그래프가 제공됨을 알 수 있다. 직접 그래프를 체험해볼 수 있고, 필요한 데이터 형태와 코드도 제공된다. 

그래프는 많은 부분 커스텀이 가능하고 드래그와 같은 캔버스 기능도 사용 가능하다. 

사용예시

Ref를 이용해서 그래프 그리기 

가장 간단한 그래프를 사용해보자. Basic Force-Atlas 2 Layout이라는 그래프를 사용했다. 

사용하려고 코드를 보면 react와 어울리지 않는 "getElementById"가 나온다. 저 부분은 react와 어울리게 ref로 대체해주면 된다. antd에서 getElementById는 ref.current로 대체 가능하다. 

위 코드를 ref로 대체하면 아래와 같다. Graph객체를 만들 때 container로 들어가는 부분은 타입이 string | HTMLElement 이기 때문에 ref.current를 넣어주면 된다. 

const container = useRef();
const graph = new G6.Graph({
  container: container.current,
  width: 600,
  height: 500,
  modes: {
    default: ['zoom-canvas', 'drag-canvas', 'drag-node'],
  },
  layout: {
    type: 'forceAtlas2',
    preventOverlap: true,
    kr: 10,
    center: [250, 250],
  },
  defaultNode: {
    size: 20,
  },
});

 

세부 커스텀하기 

노드, 간선 등의 세부 커스텀이 가능하다. 아래 링크에 나와있는 내용을 바탕으로 간선을 커스텀해보겠다.

 

Arrow of Edge

A collection of charts made with the Grammar of Graphics

g6.antv.vision

const container = useRef();
 
const graph = new G6.Graph({
  container: container.current, // HTMLElement
  width: 600,
  height: 500,
  modes: {
    default: ['zoom-canvas', 'drag-canvas', 'drag-node'], // 여기서 캔버스에 대한 설정을 조정할 수 있음
  },
  layout: {
    type: 'forceAtlas2',
    preventOverlap: true,
    kr: 10,
    center: [250, 250],
  },
 
  // Node 스타일 지정
  defaultNode: {
    size: 20,
  },
 
  // Edge 스타일 지정
  defaultEdge: {
    size: 1,
    color: 'black',
    style: {
      endArrow: {
        path: 'M, 0, 0, L, 8, 4, L, 8, -4, Z',
        fill: '#e2e2e2',
      },
    },
  },
});
 
 
data.nodes.forEach((node) => {
  node.label = node.id;
});
graph.on('afterlayout', (e) => {
  graph.fitView();
});
graph.data(data);
graph.render();

결과

반응형