Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force edge direction using vis.js?

I have trouble forcing the edges in a vis network to go into one direction. The problem seems to be that the library prefers edges which are exactly 1 level long in the hierarchy.

Used layout code:

layout: {
  hierarchical: {
    direction: "LR",
    sortMethod: 'directed'
  }
}

You can see what I mean in this JSFiddle or the image below.

I would like the node 1 to be in the same line as 2 and 3, resulting in a short arrow into 4 and a long one into 6. Instead it now places 1 after 4, resulting in an edge pointing left.

Example of the problem

like image 650
Sami Avatar asked Nov 23 '25 08:11

Sami


1 Answers

Please observe the code below.

You can achieve this by forcing horizontal layout with levels defined for each node.

level 1: 1, 2, 3 level 2: 4 level 3: 5 level 4: 6, 7 level 5: 8

and so on...

const container = document.getElementById("mynetwork");
const nodes = new vis.DataSet([
    {
      id: 1,
      label: "1",
      level: 1
    },
    {
      id: 2,
      label: "2",
      level: 1
    },
    {
      id: 3,
      label: "3",
      level: 1
    },
    {
      id: 4,
      label: "4",
      level: 2
    },
    {
      id: 5,
      label: "5",
      level: 3
    },
    {
      id: 6,
      label: "6",
      level: 4
    },
    {
      id: 7,
      label: "7",
      level: 4
    },
    {
      id: 8,
      label: "8",
      level: 5
    }
  ]);

  const edges = new vis.DataSet([
    { from: 1, to: 4 },
    { from: 3, to: 4 },
    { from: 2, to: 4 },
    { from: 4, to: 5 },
    { from: 6, to: 8 },
    { from: 5, to: 7 },
    { from: 1, to: 6 },
    { from: 7, to: 8 }
  ]);
  const data = {
    nodes: nodes,
    edges: edges
  };
  const options = {
    nodes: {
      font: {
        size: 22
      },
    },
    edges: {
      font: {
        align: "top"
      },
      arrows: {
        to: { enabled: true, scaleFactor: 1, type: "arrow" }
      }
    },
    layout: {
   hierarchical: {
      enabled: true,
      levelSeparation: 200,
      nodeSpacing: 70,
      treeSpacing: 100,
      blockShifting: true,
      edgeMinimization: true,
      parentCentralization: true,
      direction: "LR", // UD, DU, LR, RL
      sortMethod: "hubsize", // hubsize, directed
    },
    },
    interaction: {
      tooltipDelay: 200,
      hover: true
    },
  };
   const network = new vis.Network(container, data, options);
#mynetwork {
  position: absolute;
  top: 0px; right: 0px; bottom: 0px; left: 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css" rel="stylesheet"/>

<div id="mynetwork">

</div>
like image 55
Evgin Avatar answered Nov 25 '25 22:11

Evgin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!