Multiple Edges between Two Nodes

2 min read

Problem

For such a data below, how to link two nodes with multiple edges?

const data = {
  nodes: [
    {
      id: 'node1',
      x: 100,
      y: 150,
      label: 'node1',
    },
    {
      id: 'node2',
      x: 300,
      y: 150,
      label: 'node2',
    },
  ],
  edges: [
    {
      source: 'node1',
      target: 'node2',
    },
    {
      source: 'node2',
      target: 'node1',
    },
  ],
};

The following code handles the graph easily:

const graph = new G6.Graph({
  container: GRAPH_CONTAINER,
  width: 500,
  height: 500,
  defaultNode: {
    style: {
      fill: '#DEE9FF',
      stroke: '#5B8FF9',
    },
    labelCfg: {
      style: {
        fontSize: 12,
      },
    },
  },
  defaultEdge: {
    shape: 'quadratic',
    style: {
      stroke: '#e2e2e2',
    },
  },
});

graph.data(data);
graph.render();

The result:

But what if we want to show 3 or more edges?

We use the data below for example:

const data = {
  nodes: [
    {
      id: 'node1',
      x: 100,
      y: 150,
      label: 'node1',
    },
    {
      id: 'node2',
      x: 300,
      y: 150,
      label: 'node2',
    },
  ],
  edges: [
    {
      source: 'node1',
      target: 'node2',
    },
    {
      source: 'node2',
      target: 'node1',
    },
    {
      source: 'node2',
      target: 'node1',
    },
  ],
};

We found that the code above can not handle this situation any more. The result:

Solution

To solve this problem, we utlize the Custom Edge of G6.

There are two tips should be taken into consideration before customize an edge:

  • We need a flag to identify whether there are more than one edges with same direction between two nodes;
  • We need a value to control the curvature of each edge to prevent overlapping.

Therefore, we add a property edgeType for each edge in its data to identify different types of edges.

The complete the code for the demo is shown below:

Now, the prolem is solved.