Network documentation

Overview

Network is a visualization to display networks and networks consisting of nodes and edges. The visualization is easy to use and supports custom shapes, styles, colors, sizes, images, and more.

The network visualization works smooth on any modern browser for up to a few thousand nodes and edges. To handle a larger amount of nodes, Network has clustering support. Network uses HTML canvas for rendering.

Every dataset is different. Nodes can have different sizes based on content, interconnectivity can be high or low etc. Because of this, network has a special option that the user can use to explore which settings may be good for you. Use configurePhysics as described in the Physics section or by example 25.

To get started with Network, install or download the vis.js library.

Contents

Example

Here a basic network example. Note that unlike the Timeline, the Network does not need the vis.css file.

More examples can be found in the examples directory.

<!doctype html>
<html>
<head>
  <title>Network | Basic usage</title>

  <script type="text/javascript" src="../../dist/vis.js"></script>
</head>

<body>

<div id="mynetwork"></div>

<script type="text/javascript">
  // create an array with nodes
  var nodes = [
    {id: 1, label: 'Node 1'},
    {id: 2, label: 'Node 2'},
    {id: 3, label: 'Node 3'},
    {id: 4, label: 'Node 4'},
    {id: 5, label: 'Node 5'}
  ];

  // create an array with edges
  var edges = [
    {from: 1, to: 2},
    {from: 1, to: 3},
    {from: 2, to: 4},
    {from: 2, to: 5}
  ];

  // create a network
  var container = document.getElementById('mynetwork');
  var data= {
    nodes: nodes,
    edges: edges,
  };
  var options = {
    width: '400px',
    height: '400px'
  };
  var network = new vis.Network(container, data, options);
</script>

</body>
</html>

Loading

Install or download the vis.js library. in a subfolder of your project. Include the library script in the head of your html code:

<script type="text/javascript" src="vis/dist/vis.js"></script>
The constructor of the Network is vis.Network.
var network = new vis.Network(container, data, options);
The constructor accepts three parameters:

Data format

The data parameter of the Network constructor is an object which can contain different types of data. The following properties are supported in the data object:

Nodes

Nodes typically have an id and label. A node must contain at least a property id. Nodes can have extra properties, used to define the shape and style of the nodes.

A JavaScript Array with nodes is constructed like:

var nodes = [
  {
    id: 1,
    label: 'Node 1'
  },
  // ... more nodes
];
Alternatively, a vis DataSet can also be used:
var nodes = new vis.DataSet();
nodes.add([
    {id: '1', label: 'Node 1'},
    {id: '2', label: 'Node 2'},
    {id: '3', label: 'Node 3'},
    {id: '4', label: 'Node 4'},
    // ... more nodes
]);
When using a DataSet, the network is automatically updating to changes in the DataSet.

Nodes support the properties listed below. Each node can be configured individually using the properties highlighted in green over at the Nodes configuration.

Name Type Required Description
group Number | String no A group number or name. The type can be number, string, or an other type. All nodes with the same group get the same color schema.
allowedToMoveX Boolean no If allowedToMoveX is false, then the node will not move in the X direction from its position.
allowedToMoveY Boolean no If allowedToMoveY is false, then the node will not move in the Y direction from its position.
id Number | String yes A unique id for this node. Nodes may not have duplicate id's. Id's do not need to be consecutive. An id is normally a number, but may be any type.
level number no This level is used in the hierarchical layout. If this is not selected, the level does not do anything. This must be a postive number (min value: 0). Fractions are possible but only integers are supported.
label string no Text label to be displayed in the node or under the image of the node. Multiple lines can be separated by a newline character \n .
title string | function | Element no Title to be displayed when the user hovers over the node. The title can be an HTML element or a string containing plain text or HTML. When title is a function, the returned result is displayed as tooltip, and returning undefined will prevent the tooltip from being displayed.
value number no A value for the node. The radius of the nodes will be scaled automatically from minimum to maximum value. Only applicable when the shape of the node is dot. If a radius is provided for the node too, it will override the radius calculated from the value.
x number no Horizontal position in pixels. The horizontal position of the node will be fixed unless combined with the allowedToMoveX:true option. The vertical position y may remain undefined. This does not work with hierarchical layout.
y number no Vertical position in pixels. The vertical position of the node will be fixed unless combined with the allowedToMoveY:true option. The horizontal position x may remain undefined. This does not work with hierarchical layout.

Edges

Edges are connections between nodes. An edge must at least contain properties from and to, both referring to the id of a node. Edges can have extra properties, used to define the type and style.

A JavaScript Array with edges is constructed as:

var edges = [
  {
    from: 1,
    to: 3
  },
  // ... more edges
];
Alternatively, a vis DataSet can also be used:
var edges = new vis.DataSet();
edges.add([
    {from: '1', to: '2'},
    {from: '1', to: '3'},
    {from: '2', to: '4'},
    {from: '2', to: '5'},
    // ... more edges
]);
When using a DataSet, the network is automatically updating to changes in the DataSet.

Edges support properties listed below. Each edge can be configured individually using the properties highlighted in green over at the Edges configuration.

Name Type Required Description
from Number | String yes The id of a node where the edge starts. The type must correspond with the type of the node id's. This is normally a number, but can be any type.
label string no Text label to be displayed halfway the edge.
length number no The resting length of the edge when modeled as a spring. By default the springLength determined by the physics is used. By using this setting you can make certain edges have different resting lengths.
title string | function no Title to be displayed when the user hovers over the edge. The title can be an HTML element or a string containing plain text or HTML. When title is a function, the returned result is displayed as tooltip, and returning undefined will prevent the tooltip from being displayed.
to Number | String yes The id of a node where the edge ends. The type must correspond with the type of the node id's. This is normally a number, but can be any type.
value number no A value for the edge. The width of the edges will be scaled automatically from minimum to maximum value. If a width is provided for the edge too, it will override the width calculated from the value.

DOT language

Network supports data in the DOT language. To provide data in the DOT language, the data object must contain a property dot with a String containing the data.

Example usage:

// provide data in the DOT language
var data = {
  dot: 'dinetwork {1 -> 1 -> 2; 2 -> 3; 2 -- 4; 2 -> 1 }'
};

// create a network
var network = new vis.Network(container, data);

Gephi import (JSON)

network can import data straight from an exported json file from gephi. You can get the JSON exporter here: https://marketplace.gephi.org/plugin/json-exporter/. An example exists showing how to get a JSON file into Vis: 30_importing_from_gephi.

Example usage:

// load the JSON file containing the Gephi network.
var gephiJSON = loadJSON("./data/WorldCup2014.json"); // code in example 30

// create a data object with the gephi key:
var data = {
  gephi: gephiJSON
};

// create a network
var network = new vis.Network(container, data);
Alternatively you can use the parser manually:
// load the JSON file containing the Gephi network.
var gephiJSON = loadJSON("./data/WorldCup2014.json"); // code in example 30

// parse the gephi file to receive an object
// containing nodes and edges in vis format.
var parsed = vis.network.gephiParser.parseGephi(gephiJSON);

// provide data in the normal fashion
var data = {
  nodes: parsed.nodes,
  edged: parsed.edges
};

// create a network
var network = new vis.Network(container, data);

Gephi parser options

There are a few options you can use to tell Vis what to do with the data from Gephi.
var parserOptions = {
  allowedToMove: false,
  parseColor: false
}
var parsed = vis.network.gephiParser.parseGephi(gephiJSON, parserOptions);
Name Type Default Description
allowedToMove Boolean false If true, the nodes will move according to the physics model after import. If false, the nodes do not move at all.
parseColor Boolean false If true, the color will be parsed by the vis parser, generating extra colors for the borders, highlighs and hover. If false, the node will be the supplied color.

Configuration options

Options can be used to customize the network. Options are defined as a JSON object. All options are optional.

var options = {
  width:  '100%',
  height: '400px',
  edges: {
    color: 'red',
    width: 2
  }
};

The following options are available.

Name Type Default Description
clickToUse boolean false When a Network is configured to be clickToUse, it will react to mouse, touch, and keyboard events only when active. When active, a blue shadow border is displayed around the Network. The Network is set active by clicking on it, and is changed to inactive again by clicking outside the Network or by pressing the ESC key.
physics Object none Configuration of the physics system governing the simulation of the nodes and edges. Barnes-Hut nBody simulation is used by default. See section Physics for an overview of the available options.
configurePhysics Boolean false Enabling this setting will create a physics configuration div above the network. You can use this to fine tune the physics system to suit your needs. Because of the many possible configurations, there is not a one-size-fits-all setting. By using this tool, you can adapt the physics to your dataset.
dataManipulation Object none Settings for manipulating the Dataset. See section Data manipulation for an overview of the available options.
clustering Object none Clustering configuration. Clustering is turned off by default. See section Clustering for an overview of the available options.
edges Object none Configuration options applied to all edges. See section Edges configuration for an overview of the available options.
freezeForStabilization Boolean false With the advent of the storePositions() function, the positions of the nodes can be saved after they are stabilized. The smoothCurves require support nodes and those positions are not stored. In order to speed up the initialization of the network by using storePositions() and loading the nodes with the stored positions, the freezeForStabilization option freezes all nodes that have been supplied with an x and y position in place during the stabilization. That way only the support nodes for the smooth curves have to stabilize, greatly speeding up the stabilization process with cached positions.
groups Object none It is possible to specify custom styles for groups. Each node assigned a group gets the specified style. See Groups configuration for an overview of the available styles and an example.
height String "400px" The height of the network in pixels or as a percentage.
hover Boolean false Enabling the change of the colors of nodes and edges when the mouse hovers over them. Enabling this may have a minor impact on performance.
keyboard Object none Configuration options for shortcuts keys. Shortcut keys are turned off by default. See section Keyboard navigation for an overview of the available options.
dragNetwork Boolean true Toggle if the network can be dragged. This will not affect the dragging of nodes.
dragNodes Boolean true Toggle if the nodes can be dragged. This will not affect the dragging of the network.
hideNodesOnDrag Boolean false Toggle if the nodes are drawn during a drag. This can greatly improve performance if you have many nodes.
hideEdgesOnDrag Boolean false Toggle if the edges are drawn during a drag. This can greatly improve performance if you have many edges.
navigation Object none Configuration options for the navigation controls. See section Navigation controls for an overview of the available options.
nodes Object none Configuration options applied to all nodes. See section Nodes configuration for an overview of the available options.
smoothCurves Boolean || object object If true, edges are drawn as smooth curves. This is more computationally intensive since the edge now is a quadratic Bezier curve. This can be further configured by the options below.
smoothCurves.dynamic Boolean true By default, the edges are dynamic. This means there are support nodes placed in the middle of the edge. This support node is also handed by the physics simulation. If false, the smoothness will be based on the relative positions of the to and from nodes. This is computationally cheaper but there is no self organisation.
smoothCurves.type String "continuous" This option only affects NONdynamic smooth curves. The supported types are: continuous, discrete, diagonalCross, straightCross, horizontal, vertical. The effects of these types are shown in examples 26 and 27
smoothCurves.roundness Number 0.5 This only affects NONdynamic smooth curves. The roundness can be tweaked with the parameter. The value range is from 0 to 1 with a maximum roundness at 0.5.
selectable Boolean true If true, nodes in the network can be selected by clicking them. Long press can be used to select multiple nodes.
stabilize Boolean true If true, the network is stabilized before displaying it. If false, the nodes move to a stabe position visibly in an animated way.
stabilizationIterations Number 1000 If stabilize is set to true, this number is the (maximum) amount of physics steps the stabilization process takes before showing the result. If your simulation takes too long to stabilize, this number can be reduced. On the other hand, if your network is not stabilized after loading, this number can be increased.
zoomExtentOnStabilize Boolean true When the internal stabilize function is called because the stabilize option is set to true OR the hierarchical system (re)initializes, a call to zoomExtent is done by default. By setting this to false, you can avoid this call.
width String "400px" The width of the network in pixels or as a percentage.
zoomable Boolean true Toggle if the network can be zoomed.

Nodes configuration

Nodes can be configured with different styles and shapes. To configure nodes, provide an object named nodes in the options for the Network.

For example to give the nodes a custom color, shape, and size:

var options = {
  // ...
  nodes: {
    color: {
      background: 'white',
      border: 'red',
      highlight: {
        background: 'pink',
        border: 'red'
      }
    },
    shape: 'star',
    radius: 24
  }
};

The following options are available for nodes. These options must be created inside an object nodes in the networks options object.

All options in green boxes can be defined per-node as well. All options defined per-node override these global settings.
borderWidth Number 1 The width of the border of the node when it is not selected, automatically limited by the width of the node.
borderWidthSelected Number undefined The width of the border of the node when it is selected. If left at undefined, double the borderWidth will be used.
color String | Object Object Color for the node.
color.background String #97C2FC Background color for the node.
color.border String #2B7CE9 Border color for the node.
color.highlight String | Object Object Color of the node when selected.
color.highlight.background String #D2E5FF Background color of the node when selected.
color.highlight.border String #2B7CE9 Border color of the node when selected.
color.hover.background String #D2E5FF Background color of the node when the node is hovered over and the hover option is enabled.
color.hover.border String #2B7CE9 Border color of the node when the node is hovered over and the hover option is enabled.
fontColor String black Font color for label in the node.
fontFace String verdana Font face for label in the node, for example "verdana" or "arial".
fontSize Number 14 Font size in pixels for label in the node.
fontFill String undefined If a color is supplied, there will be a background color behind the label. If left undefined, no background color is shown.
fontStrokeWidth Number 0 The width of the label stroke (border around label's text) in pixels.
fontStrokeColor String 'white' The color of the label stroke.
shape string 'ellipse' Define the shape for the node. Choose from ellipse (default), circle, box, database, image, circularImage, label, dot, star, triangle, triangleDown, and square.

In case of image and circularImage, a property with name image must be provided, containing image urls.

The shapes dot, star, triangle, triangleDown, and square, are scalable. The size is determined by the properties radius or value.

When a property label is provided, this label will be displayed inside the shape in case of shapes box, circle, ellipse, and database. For all other shapes, the label will be displayed right below the shape. This shape can be overridden by a group shape, or by a shape of an individual node.
image String undefined Default image url for the nodes. only applicable to shape image.
brokenImage String undefined Image url to use in the event that the url specified in the image property fails to load. only applicable to shape image.
mass number 1 When using the Barnes Hut simulation method (which is selected by default), the mass of a node determines the gravitational repulsion during the simulation. Higher mass will push other nodes further away. Preferably use the physics configuration to alter the simulation.
widthMin Number 16 The minimum width for a scaled image. Only applicable to shape image. This only does something if you supply a value.
widthMax Number 64 The maximum width for a scaled image. Only applicable to shape image. This only does something if you supply a value.
radius Number 10 The default radius for a node. Only applicable to shapes dot, star, triangle, triangleDown, and square.
radiusMin Number 10 The minimum radius for a scaled node. Only applicable to shapes dot, star, triangle, triangleDown, and square. This only does something if you supply a value.
radiusMax Number 30 The maximum radius for a scaled node. Only applicable to shapes dot, star, triangle, triangleDown, and square. This only does something if you supply a value.

Edges configuration

Edges can be configured with different length and styling. To configure edges, provide an object named edges in the options for the Network. Because the length of an edge is a property of the physics simulation, you can change the length of the edge by changing the springLength in your selected physics solver. To change the edge length of individual edges, you can use the length property in the edge definition.

For example to set the width of all edges to 2 pixels and give them a red color:

var options = {
  // ...
  edges: {
    color: 'red',
    width: 2
  }
};

The following options are available for edges. These options must be created inside an object edges in the networks options object. All options in green boxes can be defined per-edge as well. All options defined per-edge override these global settings.

Name Type Default Description
arrowScaleFactor Number 1 If you are using arrows, this will scale the arrow. Values < 1 give smaller arrows, > 1 larger arrows. Default: 1.
color String | Object Object Color for the edge.
color.color String #848484 Color of the edge when not selected.
color.highlight String #848484 Color of the edge when selected.
color.hover String #848484 Color of the edge when the edge is hovered over and the hover option is enabled.
hoverWidth Number 1.5 This determines the thickness of the edge if it is hovered over. This will only manifest when the hover option is enabled.
dash Object Object Object containing properties for dashed lines. Available properties: length, gap, altLength.
dash.altLength number undefined Length of the alternated dash in pixels on a dashed line. Specifying dash.altLength allows for creating a dashed line with a dash-dot style, for example when dash.length=10 and dash.altLength=5. See also the option dahs.length. Only applicable when the line style is dash-line.
dash.length number 10 Length of a dash in pixels on a dashed line. Only applicable when the line style is dash-line.
dash.gap number 5 Length of a gap in pixels on a dashed line. Only applicable when the line style is dash-line.
fontColor String #343434 Font color for the text label of the edge. Only applicable when property label is defined.
fontFace String arial Font face for the text label of the edge, for example "verdana" or "arial". Only applicable when property label is defined.
fontSize Number 14 Font size in pixels for the text label of the edge. Only applicable when property label is defined.
fontFill string white Font fill for the background color of the text label of the edge. Only applicable when property label is defined.
fontStrokeWidth Number 0 The width of the label stroke (border around label's text) in pixels. Only applicable when property label is defined.
fontStrokeColor String 'white' The color of the label stroke. Only applicable when property label is defined.
inheritColor String | Boolean from Possible values: "to","from", true, false. If this value is set to false, the edge color information is used. If the value is set to true or "from", the color data from the borders of the "from" node is used. If this value is "to", the color data from the borders of the "to" node is used.
labelAlignment String horizontal Possible values: "line-above", "line-center", "line-below". The alignment of the label when drawn on the edge. If horizontal it will align the label absolute horizontial.
style string line Define a line style for the edge. Choose from line (default), arrow, arrow-center, or dash-line.
width number 1 Width of the line in pixels. The width will override a specified value, if a value is specified too.
widthSelectionMultiplier Number 2 Determines the thickness scaling of an selected edge. This is applied when an edge, or a node connected to it, is selected.
widthMin Number 1 The minimum thickness of the line when using per-edge defined values. This does nothing if you have not defined a value.
widthMax Number 15 The maximum thickness of the line when using per-edge defined values. This does nothing if you have not defined a value.

Groups configuration

It is possible to specify custom styles for groups of nodes. Each node having assigned to this group gets the specified style. The options groups is an object containing one or multiple groups, identified by a unique string, the groupname.

A group can have the following styles:

var options = {
// ...

groups: {
  mygroup: {
    shape: 'circle',
    color: {
      border: 'black',
      background: 'white',
      highlight: {
        border: 'yellow',
        background: 'orange'
      }
    }
    fontColor: 'red',
    fontSize: 18
  }
  // add more groups here
}
};

var nodes = [
{id: 1, label: 'Node 1'},                    // will get the default style
{id: 2, label: 'Node 2', group: 'mygroup'},  // will get the style from 'mygroup'
// ... more nodes
];

The following styles are available for groups:

Name Type Default Description
color String | Object Object Color of the node
color.border String "#2B7CE9" Border color of the node
color.background String "#97C2FC" Background color of the node
color.highlight String | Object "#D2E5FF" Default color of the node when the node is selected. In case of a string, the color is applied to both border and background of the node.
color.highlight.background String "#D2E5FF" Background color of the node when selected.
color.highlight.border String "#D2E5FF" Border color of the node when selected.
image String none Default image for the nodes. Only applicable in combination with shape image.
fontColor String "black" Font color of the node.
fontFace String "sans" Font name of the node, for example "verdana" or "arial".
fontSize Number 14 Font size for the node in pixels.
fontStrokeWidth Number 0 The width of the label stroke (border around label's text) in pixels.
fontStrokeColor String "white" The color of the label stroke.
shape String "ellipse" Choose from ellipse (default), circle, box, database, image, label, dot, star, triangle, triangleDown, and square. In case of image, a property with name image must be provided, containing image urls.
radius Number 5 Default radius for the node. Only applicable in combination with shapes box and dot.

Physics

The original simulation method was based on particel physics with a repulsion field (potential) around each node, and the edges were modelled as springs. The new system employed the Barnes-Hut gravitational simulation model. The edges are still modelled as springs. To unify the physics system, the damping, repulsion distance and edge length have been combined in an physics option. To retain good behaviour, both the old repulsion model and the Barnes-Hut model have their own parameters. If no options for the physics system are supplied, the Barnes-Hut method will be used with the default parameters. If you want to customize the physics system easily, you can use the configurePhysics option.
When using the hierarchical display option, hierarchicalRepulsion is automatically used as the physics solver. Similarly, if you use the hierarchicalRepulsion physics option, hierarchical display is automatically turned on with default settings.

Note: if the behaviour of your network is not the way you want it, use configurePhysics as described below or by example 25.

// These variables must be defined in an options object named physics.
// If a variable is not supplied, the default value is used.
var options = {
  physics: {
      barnesHut: {
          enabled: true,
          gravitationalConstant: -2000,
          centralGravity: 0.1,
          springLength: 95,
          springConstant: 0.04,
          damping: 0.09
      },
      repulsion: {
          centralGravity: 0.1,
          springLength: 50,
          springConstant: 0.05,
          nodeDistance: 100,
          damping: 0.09
      },
      hierarchicalRepulsion: {
          centralGravity: 0.5,
          springLength: 150,
          springConstant: 0.01,
          nodeDistance: 60,
          damping: 0.09
      }
  }
barnesHut:
Name Type Default Description
enabled Boolean true This switches the Barnes-Hut simulation on or off. If it is turned off, the old repulsion model is used. Barnes-Hut is generally faster and yields better results.
gravitationalConstant Number -2000 This is the gravitational constand used to calculate the gravity forces. More information is available here.
centralGravity Number 0.1 The central gravity is a force that pulls all nodes to the center. This ensures independent groups do not float apart.
springLength Number 95 In the previous versions this was a property of the edges, called length. This is the length of the springs when they are at rest. During the simulation they will be streched by the gravitational fields. To greatly reduce the edge length, the gravitationalConstant has to be reduced as well.
springConstant Number 0.04 This is the spring constant used to calculate the spring forces based on Hooke′s Law. More information is available here.
damping Number 0.09 This is the damping constant. It is used to dissipate energy from the system to have it settle in an equilibrium. More information is available here.
repulsion:
Name Type Default Description
centralGravity Number 0.1 The central gravity is a force that pulls all nodes to the center. This ensures independent groups do not float apart.
nodeDistance Number 100 This parameter is used to define the distance of influence of the repulsion field of the nodes. Below half this distance, the repulsion is maximal and beyond twice this distance the repulsion is zero.
springLength Number 50 In the previous versions this was a property of the edges, called length. This is the length of the springs when they are at rest. During the simulation they will be streched by the gravitational fields. To greatly reduce the edge length, the gravitationalConstant has to be reduced as well.
springConstant Number 0.05 This is the spring constant used to calculate the spring forces based on Hooke′s Law. More information is available here.
damping Number 0.09 This is the damping constant. It is used to dissipate energy from the system to have it settle in an equilibrium. More information is available here.
hierarchicalRepulsion:
Name Type Default Description
centralGravity Number 0.5 The central gravity is a force that pulls all nodes to the center. This ensures independent groups do not float apart.
nodeDistance Number 60 This parameter is used to define the distance of influence of the repulsion field of the nodes. Below half this distance, the repulsion is maximal and beyond twice this distance the repulsion is zero.
springLength Number 100 In the previous versions this was a property of the edges, called length. This is the length of the springs when they are at rest. During the simulation they will be streched by the gravitational fields. To greatly reduce the edge length, the gravitationalConstant has to be reduced as well.
springConstant Number 0.01 This is the spring constant used to calculate the spring forces based on Hooke′s Law. More information is available here.
damping Number 0.09 This is the damping constant. It is used to dissipate energy from the system to have it settle in an equilibrium. More information is available here.

Configuration:

Every dataset is different. Nodes can have different sizes based on content, interconnectivity can be high or low etc. Because of this, network has a special option that the user can use to explore which settings may be good for him or her. This is ment to be used during the development phase when you are implementing vis.js. Once you have found settings you are happy with, you can supply them to network using the physics options as described above. On start, the default settings will be loaded. Keep in mind that selecting the hierarchical simulation mode disables smooth curves. These will not be enabled again afterwards.
var options = {
    configurePhysics:true
}

Data manipulation

By using the data manipulation feature of the network you can dynamically create nodes, connect nodes with edges, edit nodes or delete nodes and edges. The toolbar is fully HTML and CSS so the user can style this to their preference. To control the behaviour of the data manipulation, users can insert custom functions into the data manipulation process. For example, an injected function can show an detailed pop-up when a user wants to add a node. In example 21, two functions have been injected into the add and edit functionality. This is described in more detail in the next subsection. To correctly display the manipulation icons, the vis.css file must be included. The user is free to alter or overload the CSS classes but without them the navigation icons are not visible.

// These variables must be defined in an options object named dataManipulation.
// If a variable is not supplied, the default value is used.
var options = {
    dataManipulation: {
      enabled: false,
      initiallyVisible: false
    }
}
// OR to just load the module with default values:
var options = {
    dataManipulation: true
}
Name Type Default Description
enabled Boolean false Enabling or disabling of the data manipulation toolbar. If it is initially hidden, an edit button appears in the top left corner.
initiallyVisible Boolean false Initially hide or show the data manipulation toolbar.

Data manipulation: custom functionality

Users can insert custom functions into the add node, edit node, connect nodes, and delete selected operations. This is done by supplying them in the options. If the callback is NOT called, nothing happens. Example 21 has two working examples for the add and edit functions. The data the user is supplied with in these functions has been described in the code below. For the add data, you can add any and all options that are accepted for node creation as described above. The same goes for edit, however only the fields described in the code below contain information on the selected node. The callback for connect accepts any options that are used for edge creation. Only the callback for delete selected requires the same data structure that is supplied to the user.

If there is no injected function supplied for the edit operation, the button will not be shown in the toolbar.

// If a variable is not supplied, the default value is used.
var options = {
    dataManipulation: true,
    onAdd: function(data,callback) {
        /** data = {id: random unique id,
        *           label: new,
        *           x: x position of click (canvas space),
        *           y: y position of click (canvas space),
        *           allowedToMoveX: true,
        *           allowedToMoveY: true
        *          };
        */
        var newData = {..}; // alter the data as you want.
                            // all fields normally accepted by a node can be used.
        callback(newData);  // call the callback to add a node.
    },
    onEdit: function(data,callback) {
        /** data = {id:...,
        *           label: ...,
        *           group: ...,
        *           shape: ...,
        *           color: {
        *             background:...,
        *             border:...,
        *             highlight: {
        *               background:...,
        *               border:...
        *             }
        *           }
        *          };
        */
        var newData = {..}; // alter the data as you want.
                            // all fields normally accepted by a node can be used.
        callback(newData);  // call the callback with the new data to edit the node.
    }
    onEditEdge: function(data,callback) {
        /** data = {id: edgeID,
        *           from: nodeId1,
        *           to: nodeId2,
        *          };
        */
        var newData = {..}; // alter the data as you want, except for the ID.
                            // all fields normally accepted by an edge can be used.
        callback(newData);  // call the callback with the new data to edit the edge.
    }
    onConnect: function(data,callback) {
        // data = {from: nodeId1, to: nodeId2};
        var newData = {..};      // check or alter data as you see fit.
        callback(newData);       // call the callback to connect the nodes.
    },
    onDelete: function(data,callback) {
        // data = {nodes: [selectedNodeIds], edges: [selectedEdgeIds]};
        var newData = {..}; // alter the data as you want.
                            // the same data structure is required.
        callback(newData);  // call the callback to delete the objects.
    }
};

Because the interface elements are CSS and HTML, the user will have to correct for size changes of the canvas. To facilitate this, a new event has been added called resize. A function can be bound to this event. This function is supplied with the new widht and height of the canvas. The CSS can then be updated accordingly. An code snippet from example 21 is shown below.

network.on("resize", function(params) {console.log(params.width,params.height)});

Clustering

The network now supports dynamic clustering of nodes. This allows a user to view a very large dataset (> 50.000 nodes) without sacrificing performance. When loading a large dataset, the nodes are clustered initially (this may take a small while) to have a responsive visualization to work with. The clustering is both outside-in and inside-out. Outside-in means that nodes with only one connection will be contained, or clustered, in the node it is connected to. Inside-out clustering first determines which nodes are hubs. Hubs are defined as the nodes with the top 3% highest amount of connections (assuming normal distribution). These hubs then "grow", meaning they contain the nodes they are connected to within themselves. The edges that were connected to the nodes that are absorbed will be reconnected to the cluster.

A cluster is just a node that has references to the nodes and edges it contains. It has an internal counter to keep track of its size, which is then used to calculate the required forces. The contained nodes are removed from the global nodes index, greatly speeding up the system.

The clustering has the following user-configurable settings. The default values have been tested with the Network examples and work well. The default state for clustering is off.

// These variables must be defined in an options object named clustering.
// If a variable is not supplied, the default value is used.
var options = {
    clustering: {
      initialMaxNodes: 100,
      clusterThreshold:500,
      reduceToNodes:300,
      chainThreshold: 0.4,
      clusterEdgeThreshold: 20,
      sectorThreshold: 100,
      screenSizeThreshold: 0.2,
      fontSizeMultiplier:  4.0,
      maxFontSize: 1000,
      forceAmplification:  0.1,
      distanceAmplification: 0.1,
      edgeGrowth: 20,
      nodeScaling: {width:  1,
                    height: 1,
                    radius: 1},
      maxNodeSizeIncrements: 600,
      activeAreaBoxSize: 100,
      clusterLevelDifference: 2
    }
}
// OR to just load the module with default values:
var options = {
    clustering: true
}
Name Type Default Description
initialMaxNodes Number 100 If the initial amount of nodes is larger than this value, clustering starts until the total number of nodes is less than this value.
clusterThreshold Number 500 While zooming in and out, clusters can open up. Once there are more than absoluteMaxNumberOfNodes nodes, clustering starts until reduceToMaxNumberOfNodes nodes are left. This is done to ensure performance is continuously fluid.
reduceToNodes Number 300 While zooming in and out, clusters can open up. Once there are more than absoluteMaxNumberOfNodes nodes, clustering starts until reduceToMaxNumberOfNodes nodes are left. This is done to ensure performance is continiously fluid.
chainThreshold Number 0.4 Because of the clustering methods used, long chains of nodes can be formed. To reduce these chains, this threshold is used. A chainThreshold of 0.4 means that no more than 40% of all nodes are allowed to be a chain node (two connections). If there are more, they are clustered together.
clusterEdgeThreshold Number 20 This is the absolute edge length threshold in pixels. If the edge is smaller on screen (that means zooming out reduces this length) the node will be clustered. This is triggered when zooming out.
sectorThreshold Integer 50 If a cluster larger than sectorThreshold is opened, a seperate instance called a sector, will be created. All the simulation of nodes outside of this instance will be paused. This is to maintain performance and clarity when examining large clusters. A sector is collapsed when zooming out far enough. Also, when opening a cluster, if this cluster is smaller than this value, it is fully unpacked.
screenSizeThreshold Number 0.2 When zooming in, the clusters become bigger. A screenSizeThreshold of 0.2 means that if the width or height of this cluster becomes bigger than 20% of the width or height of the canvas, the cluster is opened. If a sector has been created, if the sector is smaller than 20%, we collapse this sector.
fontSizeMultiplier Number 4.0 This parameter denotes the increase in fontSize of the cluster when a single node is added to it.
maxFontSize Number 1000 This parameter denotes the largest allowed font size. If the font becomes too large, some browsers experience problems displaying this.
forceAmplification Number 0.6 This factor is used to calculate the increase of the repulsive force of a cluster. It is calculated by the following formula: repulsingForce *= 1 + (clusterSize * forceAmplification).
distanceAmplification Number 0.2 This factor is used to calculate the increase in effective range of the repulsive force of the cluster. A larger cluster has a longer range. It is calculated by the following formula: minDistance *= 1 + (clusterSize * distanceAmplification).
edgeGrowth Number 20 This factor determines the elongation of edges connected to a cluster.
nodeScaling.width Number 10 This factor determines how much the width of a cluster increases in pixels per added node.
nodeScaling.height Number 10 This factor determines how much the height of a cluster increases in pixels per added node.
nodeScaling.radius Number 10 This factor determines how much the radius of a cluster increases in pixels per added node.
maxNodeSizeIncrements Number 600 This limits the size clusters can grow to. The default value, 600, implies that if a cluster contains more than 600 nodes, it will no longer grow.
activeAreaBoxSize Number 100 Imagine a square with an edge length of activeAreaBoxSize pixels around your cursor. If a cluster is in this box as you zoom in, the cluster can be opened in a seperate sector. This is regardless of the zoom level.
clusterLevelDifference Number 2 At every clustering session, Network will check if the difference between cluster levels is acceptable. When a cluster is formed when zooming out, that is one cluster level. If you zoom out further and it encompasses more nodes, that is another level. For example: If the highest level of your network at any given time is 3, nodes that have not clustered or have clustered only once will join their neighbour with the lowest cluster level.

Network has a menu with navigation controls, which is disabled by default. It can be configured with the following settings. To correctly display the navigation icons, the vis.css file must be included. The user is free to alter or overload the CSS classes but without them the navigation icons are not visible.

// use of navigation controls
var options = {
  navigation: true
}

Keyboard navigation

The network can be navigated using shortcut keys. The default state for the keyboard navigation is off. The predefined keys can be found in the example 20_navigation.html.

// simple use of keyboard controls
var options = {
    keyboard: true
}

// advanced configuration for keyboard controls
var options = {
  keyboard: {
    speed: {
      x: 10,
      y: 10,
      zoom: 0.02
    },
    bindToWindow: true
  }
}
Name Type Default Description
speed.x Number 10 This defines the speed of the camera movement in the x direction when using the keyboard navigation.
speed.y Number 10 This defines the speed of the camera movement in the y direction when using the keyboard navigation.
speed.zoom Number 0.02 This defines the zoomspeed when using the keyboard navigation.
bindToWindow Boolean true If this is true, global keyboard events will be used. If it is false, the keyboard events are only used when the network is active. It is activated on mouseOver automatically.

Hierarchical layout

The network can be used to display nodes in a hierarchical way. This can be determined automatically, based on the amount of edges connected to each node, or defined by the user. If the user wants to manually determine the hierarchy, each node has to be supplied with a level (from 0 being heighest to n). The automatic method is shown in example 23 and the user-defined method is shown in example 24. This layout method does not support smooth curves or clustering. It automatically turns these features off.

// simple use of the hierarchical layout
var options = {
    hierarchicalLayout: true
}

// advanced configuration for hierarchical layout
var options = {
    hierarchicalLayout: {
      enabled:false,
      levelSeparation: 150,
      nodeSpacing: 100,
      direction: "UD",
      layout: "hubsize"
    }
}
// partial configuration automatically sets enabled to true
var options = {
    hierarchicalLayout: {
      nodeSpacing: 100,
      direction: "UD"
    }
}
Name Type Default Description
enabled Boolean false Enable or disable the hierarchical layout.
levelSeparation Number 150 This defines the space between levels (in the Y-direction, considering UP-DOWN direction).
nodeSpacing Number 100 This defines the space between nodes in the same level (in the X-direction, considering UP-DOWN direction). This is only relevant during the initial placing of nodes.
direction String UD This defines the direction the network is drawn in. The supported directions are: Up-Down (UD), Down-Up (DU), Left-Right (LR) and Right-Left (RL). These need to be supplied by the acronyms in parentheses.
layout String hubsize This defines the way the nodes are distributed. Available options are hubsize and direction. The default value is hubsize, meaning the node with the most edges connected to it (largest hub) is on top. Alternatively, direction arranges the nodes based on the direction of the edges. See example 32 for more information.

Localization

When using vis.js in other languages, one can use the localization option to get a localized data manipulation interface.

Name Type Default Description
locale String none Select a locale for the Network.
locales Object none A map with i18n locales.

To set a locale for the Network, specify the option locale:

var options = {
  locale: 'nl'
};

Create a new locale

To load a locale into the Timeline not supported by default, one can add a new locale to the option locales:
var options = {
  locales: {
    // create a new locale (text strings should be replaced with localized strings)
    mylocale: {
      edit: 'Edit',
      del: 'Delete selected',
      back: 'Back',
      addNode: 'Add Node',
      addEdge: 'Add Edge',
      editNode: 'Edit Node',
      editEdge: 'Edit Edge',
      addDescription: 'Click in an empty space to place a new node.',
      edgeDescription: 'Click on a node and drag the edge to another node to connect them.',
      editEdgeDescription: 'Click on the control points and drag them to a node to connect to it.',
      createEdgeError: 'Cannot link edges to a cluster.',
      deleteClusterError: 'Clusters cannot be deleted.'
    }
  },

  // use the new locale
  locale: 'mylocale'
};

Available locales

Network comes with support for the following locales:

LanguageCode
English en
en_EN
en_US
Dutch nl
nl_NL
nl_BE

Tooltips

The behaviour and style of the tooltips used to display node and edge title attributes can be customized.

// tooltip behaviour and style options
var options = {
  tooltip: {
    delay: 300,
    fontColor: "black",
    fontSize: 14, // px
    fontFace: "verdana",
    color: {
      border: "#666",
      background: "#FFFFC6"
    }
  }
}
Name Type Default Description
delay Number 300 Time in milliseconds a user must hover over a node or edge before a tooltip appears.
fontColor String "black" Default color for tooltip text.
fontSize Number 14 Size in pixels of tooltip text.
fontFace String "verdana" Font family to used for tooltip text.
color.background String "#FFFFC6" Background color for the node.
color.border String "#666" Border color for the node.

Methods

Network supports the following methods.

Method Return Type Description
getScale() Number Returns the scale of the network. This can be for animation. This scale is like a percentage, 1.0 = 100%. Zooming in is > 1.0, zooming out is < 0. Scale cannot be smaller or equal to 0.
getCenterCoordinates() Number Returns the x and y coodinates of the center of the screen (in canvas space).
getBoundingBox(nodeId) Object Returns a bounding box for the node including label in the format: {top:Number,left:Number,right:Number,bottom:Number}. These values are in canvas space.
getSelection() Array of ids Returns an array with the ids of the selected nodes. Returns an empty array if no nodes are selected. The selections are not ordered.
focusOnNode(nodeId, [options]) none This function will move the view to center on the specified node. An optional options object can submitted where you can define the animation properties.
The options that can be defined are:
scale:Number
- to zoom to that scale,
offset:{x:Number, y:Number}
- to offset the position from the center of the canvas (in pixels),
locked: boolean
- if true, the view remains locked on this node until either another focusOnNode, moveTo, releaseNode or drag is done
animation: Object || Boolean
- to define the specifics of the animation. True is animated with default settings, false is not animated.

The animation object can consist of:
duration: Number
- the duration of the animation in milliseconds,
easingFunction: String
- the easing function of the animation, available are:
linear, easeInQuad, easeOutQuad, easeInOutQuad, easeInCubic, easeOutCubic, easeInOutCubic, easeInQuart, easeOutQuart, easeInOutQuart, easeInQuint, easeOutQuint, easeInOutQuint

releaseNode() none When locked on to a node, this function releases it again. If the view is not locked onto a node due to the focusOnNode locked option, nothing happens.
DOMtoCanvas(pos) object This function converts DOM coordinates to coordinates on the canvas. Input and output are in the form of {x:xpos,y:ypos}. The DOM values are relative to the network container.
canvasToDOM(pos) object This function converts canvas coordinates to coordinates on the DOM. Input and output are in the form of {x:xpos,y:ypos}. The DOM values are relative to the network container.
moveTo(options) object This function allows you to programmatically move the view. The options that can be defined are:
position:{x:Number, y:Number}
- to move to that position (in canvas units),
scale:Number
- to zoom to that scale,
offset:{x:Number, y:Number}
- to offset the position from the center of the canvas (in DOM units),
animation: Object || Boolean
- to define the specifics of the animation.

The animation object can consist of:
duration: Number
- the duration of the animation in milliseconds,
easingFunction: String
- the easing function of the animation, available are:
linear, easeInQuad, easeOutQuad, easeInOutQuad, easeInCubic, easeOutCubic, easeInOutCubic, easeInQuart, easeOutQuart, easeInOutQuart, easeInQuint, easeOutQuint, easeInOutQuint

You will have to define at least a scale or a position. Otherwise, there is nothing to move to.
on(event, callback) none Create an event listener. The callback function is invoked every time the event is triggered. Avialable events: select. The callback function is invoked as callback(properties), where properties is an object containing event specific properties. See section Events for more information.
off(event, callback) none Remove an event listener created before via function on(event, callback). See section Events for more information.
destroy() none Remove all bindings and clean up after the Network.
redraw() none Redraw the network. Useful when the layout of the webpage changed.
setData(data,[disableStart]) none Loads data. Parameter data is an object containing nodes, edges, and options. Parameters nodes, edges are an Array. Options is a name-value map and is optional. Parameter disableStart is an optional Boolean and can disable the start of the simulation that would begin at the end of this function by default.
setOptions(options) none Set options for the network. The available options are described in the section Configuration Options.
selectNodes(selection, [highlightEdges]) none Select nodes. selection is an array with ids of nodes to be selected. The array selection can contain zero or multiple ids. Example usage: network.selectNodes([3, 5]); will select nodes with id 3 and 5. The highlisghEdges boolean can be used to automatically select the edges connected to the node.
getConnectedNodes(nodeId) Array Get an array of (unique) nodeIds that are directly connected to this node.
selectEdges(selection) none Select Edges. selection is an array with ids of edges to be selected. The array selection can contain zero or multiple ids. Example usage: network.selectEdges([3, 5]); will select edges with id 3 and 5.
setSize(width, height) none Parameters width and height are strings, containing a new size for the visualization. Size can be provided in pixels or in percentages.
getPositions([nodeIds]) Object This will return an object of all nodes' positions. Data can be accessed with object[nodeId].x and .y. You can optionally supply an id as string or number or an array of ids. If no id or array of ids have been supplied, all positions are returned.
storePositions() none When using the vis.DataSet to load your nodes into the network, this method will put the X and Y positions of all nodes into that dataset. It will also include allowedToMoveX and allowedToMoveY with the correct values. If you're loading your nodes from a database and have this dynamically coupled with the DataSet, you can use this to stablize your network once, then save the positions in that database through the DataSet so the next time you load the nodes, stabilization will be near instantaneous. If the nodes are still moving and you're using dynamic smooth edges (which is on by default), you can use the option freezeForStabilization to improve initialization time.

NOTE:This method does not work with the hierarchical layout because the hierarchical algorithm is assigning X Y positions on load, regardless of the ones you supply it with.
zoomExtent([options]) none Scales the network so all the nodes are in center view. Optionally you can supply options for animation. These options can just be a boolean. When true, the zoom is animated, when false there is no animation. Alternatively, you can supply an object.

The object can consist of:
nodes: [nodeIds]
- an optional subset of nodes to zoom in on,
duration: Number
- the duration of the animation in milliseconds,
easingFunction: String
- the easing function of the animation, available are:
linear, easeInQuad, easeOutQuad, easeInOutQuad, easeInCubic, easeOutCubic, easeInOutCubic, easeInQuart, easeOutQuart, easeInOutQuart, easeInQuint, easeOutQuint, easeInOutQuint

Events

Network fires events after one or multiple nodes are selected or deselected. The event can be catched by creating a listener.

Here an example on how to catch a select event.

network.on('select', function (properties) {
  alert('selected nodes: ' + properties.nodes);
});

A listener can be removed via the function off:

function onSelect (properties) {
  alert('selected nodes: ' + properties.nodes);
}

// add event listener
network.on('select', onSelect);

// do stuff...

// remove event listener
network.off('select', onSelect);

The following events are available.

name Description Properties
animationFinished Fired after an animation is finished. none
select Fired after the user selects or deselects a node by clicking it. Not fired when the method setSelectionis executed.
  • nodes: an array with the ids of the selected nodes
  • edges: an array with the ids of the selected edges
click Fired after the user clicks or taps on a touchscreen.
  • nodes: an array with the ids of the selected nodes
  • edges: an array with the ids of the selected edges
  • pointer.DOM:object containing XY coordinates in the DOM
  • pointer.canvas:object containing XY coordinates in the canvas
doubleClick Fired after the user double clicks or double taps on a touchscreen.
  • nodes: an array with the ids of the selected nodes
  • edges: an array with the ids of the selected edges
  • pointer.DOM:object containing XY coordinates in the DOM
  • pointer.canvas:object containing XY coordinates in the canvas
hoverNode Fired when the mouse is moved over a node (assuming the hover option is enabled).
  • node: an object with the id of the hovered node.
blurNode Fired when the mouse is moved off a node (assuming the hover option is enabled).
  • node: an object with the id of the hovered node.
resize Fired when the size of the canvas has been resized, either by a redraw call when the container div has changed in size, a setSize() call with new values or a setOptions() with new width and/or height values.
  • width: the new width of the canvas
  • height: the new height of the canvas
  • oldWidth: the old width of the canvas
  • oldHeight: the old height of the canvas
dragStart Fired when a node is being dragged.
  • nodeIds: Array of ids of the nodes that are being dragged
dragEnd Fired when the dragging of a node(s) has ended.
  • nodeIds: Array of ids of the nodes that were being dragged
startStabilization Fired once when the network starts the physics calculation. This ends with the stabilized event. none
stabilized Fired every time the network has been stabilized. This event can be used to trigger the .storePositions() function after stabilization. Fired with an object having the following properties:
  • iterations: number of iterations used to stabilize
viewChanged Fired when the view has changed. This is when the network has moved or zoomed. none
zoom Fired when the network has zoomed. This event can be used to trigger the .storePositions() function after stabilization.
  • direction: "+" or "-"

Data policy

All code and data is processed and rendered in the browser. No data is sent to any server.