DEV Community

Aaron Gong
Aaron Gong

Posted on

Adding @antv/g6 To Streamlit Custom Component

Steps To Implement

  • You need to already create the vite vanilla JS custom component in part 2 or this series
  • From the template folder
  • Add the @antv/g9 library
cd vite_vanilla_component/frontend
npm i @antv/g6
Enter fullscreen mode Exit fullscreen mode
  • insert the code below just after import { Streamlit } from 'streamlit-component-lib' on or near the top of the main.js file
import G6 from '@antv/g6';

const gdata = {
  nodes: [
    { id: 'node1', x: 50, y: 350, label: 'A', },
    { id: 'node2', x: 250, y: 150, label: 'B', },
    { id: 'node3', x: 450, y: 350, label: 'C', },
  ],
  edges: [],
};

for (let i = 0; i < 10; i++) {
  gdata.edges.push({ source: 'node1', target: 'node2', label: `${i}th edge of A-B`, });
}
for (let i = 0; i < 5; i++) {
  gdata.edges.push({ source: 'node2', target: 'node3', label: `${i}th edge of B-C`, });
}

const container = document.body.appendChild(document.createElement("div"))
container.setAttribute('id', 'container');
G6.Util.processParallelEdges(gdata.edges);

const width = document.getElementById('container').scrollWidth;
const height = document.getElementById('container').scrollHeight || 500;
console.log(width, height)
const graph = new G6.Graph({
  container: 'container',
  width,
  height,
  // translate the graph to align the canvas's center, support by v3.5.1
  fitCenter: true,
  // the edges are linked to the center of source and target ndoes
  linkCenter: true,
  defaultNode: {
    type: 'circle',
    size: [40],
    color: '#5B8FF9',
    style: { fill: '#9EC9FF', lineWidth: 3, },
    labelCfg: {
      style: { fill: '#000', fontSize: 14, },
    },
  },
  defaultEdge: {
    type: 'quadratic',
    labelCfg: { autoRotate: true, },
  },
  modes: {
    default: ['drag-canvas', 'drag-node'],
  },
  nodeStateStyles: {
    hover: { fillOpacity: 0.8, },
    selected: { lineWidth: 5, },
  },
});
graph.data(gdata);
graph.render();
Enter fullscreen mode Exit fullscreen mode

Running

The steps to run are the same as in previous article (right click and open new tab).

You should see the following when navigating to the component url:

image


Further Improvements

The following are improvements that can be done once the code is added:

  • Allow end-user to pass in g6 config, nodes and edges from python code
  • Add graph event listeners to record last clicked node
  • Modify the button to send last clicked node information back

Top comments (0)