Show the code for this example
Hide the code for this example
$(function(){
var nodeCount = 10;
var edgeCount = 12;
var demoNodes = [];
var demoEdges = [];
for (var i = 0; i < nodeCount; i++) {
demoNodes.push({
data: {
id: "n" + i,
weight: Math.round( Math.random() * 100 )
}
});
}
for (var i = 0; i < nodeCount; i++) {
demoEdges.push({
data: {
id: "e" + (i * 2),
source: "n" + ((i + 1) >= nodeCount ? i + 1 - nodeCount : i + 1),
target: "n" + i,
weight: 30
}
});
if (i % 2 == 0) {
demoEdges.push({
data: {
id: "e" + (i * 2 + 1),
target: "n" + i,
source: "n" + ((i + 3) >= nodeCount ? i + 3 - nodeCount : i + 3),
weight: 21
}
});
}
}
$('#demo').cytoscape({
elements: { // TODO specify some elements like http://cytoscapeweb.cytoscape.org/demos/simple
nodes: demoNodes,
edges: demoEdges
},
// TODO specify a nice style like http://cytoscapeweb.cytoscape.org/demos/simple
style: cytoscape.stylesheet()
.selector("node")
.css({
"content": "data(id)",
"shape": "data(shape)",
"border-width": 3,
"background-color": "#DDD",
"border-color": "#555"
})
.selector("edge")
.css({
"width": "mapData(weight, 0, 100, 1, 4)",
"target-arrow-shape": "triangle",
"source-arrow-shape": "circle",
"line-color": "#444"
})
.selector(":selected")
.css({
"background-color": "#000",
"line-color": "#000",
"source-arrow-color": "#000",
"target-arrow-color": "#000"
})
.selector(".ui-cytoscape-edgehandles-source")
.css({
"border-color": "#5CC2ED",
"border-width": 3
})
.selector(".ui-cytoscape-edgehandles-target, node.ui-cytoscape-edgehandles-preview")
.css({
"background-color": "#5CC2ED"
})
.selector("edge.ui-cytoscape-edgehandles-preview")
.css({
"line-color": "#5CC2ED"
})
.selector("node.ui-cytoscape-edgehandles-preview, node.intermediate")
.css({
"shape": "rectangle",
"width": 15,
"height": 15
})
,
ready: function(){
window.cy = this; // for debugging
var nodeCount = cy.nodes().length;
for (var i = 0; i < nodeCount; i++) {
var center = [cy.container().clientWidth / 2, cy.container().clientHeight / 2];
var angle = i / nodeCount * Math.PI * 2;
// console.log(angle);
var radius =
Math.min(cy.container().clientWidth, cy.container().clientHeight) / 2 * 0.6;
// console.log(radius);
var nodePos = [Math.cos(angle) * radius + center[0], Math.sin(angle) * radius + center[1]]
// console.log(nodePos);
cy.nodes()[i].position({x: nodePos[0], y : nodePos[1]});
}
}
});
});
Introduction
About
Cytoscape.js is an open-source graph library written in JavaScript. You can use Cytoscape.js for graph analysis and visualisation.
Cytoscape.js allows you to easily display graphs in your websites. Because Cytoscape.js allows the user to interact with the graph and the library allows the client to hook into user events, Cytoscape.js is easily integrated into your webapp, especially since Cytoscape.js supports both desktop browsers, like Chrome, and mobile browsers, like on the iPad.
Cytoscape.js also has graph analysis in mind: The library contains a slew of useful functions in graph theory. You can use Cytoscape.js headlessly on Node.js to do graph analysis in the terminal or on a web server.
The library was developed at the Donnelly Centre at the University of Toronto. It is the successor of Cytoscape Web.
Cytoscape.js & Cytoscape
Though Cytoscape.js shares its name with Cytoscape, Cytoscape.js is not Cytoscape. Cytoscape.js is a JavaScript library for programmers. It is not an app for end-users, nor can you just copy-paste some code to "automagically" make you a webapp.
Cytoscape.js is a JavaScript library: It gives you a reusable graph widget that you can integrate with the rest of your webapp with your own JavaScript code. The keen members of the audience will point out that this means that Cytoscape plugins — written in Java — will obviously not work in Cytoscape.js — written in JavaScript.
We do follow some similar philosophies with Cytoscape: Graph style and data should be separate, and the library should provide core functionality with extensions adding functionality on top of the library.
Funding
Funding for Cytoscape.js and Cytoscape is provided by NRNB (U.S. National Institutes of Health, National Center for Research Resources grant numbers P41 RR031228 and GM103504) and by NIH grants 2R01GM070743 and 1U41HG006623. The following organizations help develop Cytoscape:
ISB | UCSD | MSKCC | Pasteur | Agilent | UCSF | Unilever | Toronto | NCIBI
Notation
Architecture & API
There are two components in the architecture that a developer need concern himself in order to use Cytoscape.js, the core and the collection. In Cytoscape.js, the core is a developer's main entry point into the library. From the core, a developer can run layouts, alter the viewport, and perform other operations on the graph as a whole.
The core provides several functions to access elements in the graph. Each of these functions returns a collection, a set of elements in the graph. A set of functions are available on collections that allow the developer to filter the collection, perform operations on the collection, traverse the graph about the collection, get data about elements in the collection, and so on.
Notation
There are several types that different functions can be executed on, and the variable names used to denote these types in the documentation are outlined below:
Notation Works on
-------- --------
cy ........... the core
eles ......... a collection of one or more elements (nodes and edges)
ele .......... a collection of a single element (node or edge)
nodes ........ a collection of one or more nodes
node ......... a collection of a single node
edges ........ a collection of one or more edges
edge ......... a collection of a single edge
By default, a function returns a reference back to the calling object to allow for jQuery-like chaining (e.g. obj.fn1().fn2().fn3()
). Unless otherwise indicated in this documentation, a function is chainable in this manner unless a different return value is specified. This applies both to the core and to collections.
Position
There is an important distinction to make for position: A position may be a model position or a rendered position.
A model position — as its name suggests — is the position stored in the model for an element. An element's model position remains constant, despite changes to zoom and pan.
A rendered position is an on-screen location relative to the viewport. For example, a rendered position of { x: 100, y: 100 }
specifies a point 100 pixels to the right and 100 pixels down from the top-left corner of the viewport. An element's rendered position naturally changes as zoom and pan changes, because the element's on-screen position in the viewport changes as zooming and panning are applied.
In this documentation, "position" refers to model position unless otherwise stated.
Selectors
Notes & caveats
A selector functions similar to a jQuery selector on DOM elements, but selectors in Cytoscape.js instead work on collections.
The selectors can be combined together to make powerful queries in Cytoscape.js, for example:
// get all selected nodes with weight greater than or equal to 30
cy.elements("node[weight >= 30]:selected");
Selectors can be joined together (effectively creating a logical OR) with commas:
// get both locked nodes AND selected edges
cy.elements("node:locked, edge:selected");
It is important to note that strings need to be enclosed by quotation marks:
cy.filter("node[foo = bar]"); // this doesn't work
cy.filter("node[foo = 'bar']"); // but this does
Group & class
node
or edge
(group selector)
Matches elements based on group (node
for nodes, edge
for edges).
.className
Matches elements that have the specified class (e.g. use .foo
for a class named "foo").
Data
[name]
Matches elements if they have the specified data attribute defined aka not undefined
(e.g. [foo]
for an attribute named "foo"). Here, null
is considered a defined value.
[?name]
Matches elements if the specified data attribute is a truthy value (e.g. [?foo]
).
[!name]
Matches elements if the specified data attribute is a falsey value (e.g. [!foo]
).
[^name]
Matches elements if the specified data attribute is not defined aka undefined
(e.g [^foo]
). Here, null
is considered a defined value.
[name = value]
Matches elements if their data attribute matches a specified value (e.g. [foo = 'bar']
or [num = 2]
).
[name != value]
Matches elements if their data attribute doesn't match a specified value (e.g. [foo != 'bar']
or [num != 2]
).
[name > value]
Matches elements if their data attribute is greater than a specified value (e.g. [foo > 'bar']
or [num > 2]
).
[name >= value]
Matches elements if their data attribute is greater than or equal to a specified value (e.g. [foo >= 'bar']
or [num >= 2]
).
[name < value]
Matches elements if their data attribute is less than a specified value (e.g. [foo < 'bar']
or [num < 2]
).
[name <= value]
Matches elements if their data attribute is less than or equal to a specified value (e.g. [foo <= 'bar']
or [num <= 2]
).
[name *= value]
Matches elements if their data attribute contains the specified value as a substring (e.g. [foo *= 'bar']
).
[name ^= value]
Matches elements if their data attribute starts with the specified value (e.g. [foo ^= 'bar']
).
[name $= value]
Matches elements if their data attribute ends with the specified value (e.g. [foo $= 'bar']
).
@
(data attribute operator modifier)
Prepended to an operator so that is case insensitive (e.g. [foo @$= 'ar']
, [foo @>= 'a']
, [foo @= 'bar']
)
{}
(metadata brackets)
Use curly brackets in place of square ones to match against metadata instead of data (e.g. {degree > 2}
matches elements of degree greater than 2). The properties that are supported include degree
, indegree
, and outdegree
.
State
:animated
Matches elements that are currently being animated.
:unanimated
Matches elements that are not currently being animated.
:selected
Matches selected elements.
:unselected
Matches elements that aren't selected.
:selectable
Matches elements that are selectable.
:unselectable
Matches elements that aren't selectable.
:locked
Matches locked elements.
:unlocked
Matches elements that aren't locked.
:visible
Matches elements that are visible.
:hidden
Matches elements that are hidden.
:grabbed
Matches elements that are being grabbed by the user.
:free
Matches elements that are not currently being grabbed by the user.
:grabbable
Matches elements that are grabbable by the user.
:ungrabbable
Matches elements that are not grabbable by the user.
:removed
Matches elements that have been removed from the graph.
:inside
Matches elements that have are in the graph (they are not removed).
Style
Style in Cytoscape.js follows CSS conventions as closely as possible. In most cases, a property has the same name and behaviour as its corresponding CSS namesake. However, the properties in CSS are not sufficient to specify the style of some parts of the graph. In that case, additional properties are introduced that are unique to Cytoscape.js.
Properties
Notes
- Colours may be specified by name (e.g.
red
), hex (e.g.#ff0000
or#f00
), RGB (e.g.rgb(255, 0, 0)
), or HSL (e.g.hsl(0, 100%, 50%)
). - Values requiring a number, such as a length, can be specified in pixel values (e.g.
24px
), unitless values that are implicitly in pixels (24
), or em values (e.g.2em
). - Opacity values are specified as numbers ranging on
0 <= opacity <= 1
.
Element properties
These properties can be used on any element:
cursor
: The CSS cursor shown when the cursor is over top the element.color
: The colour of the element's label.content
: The text to display for an element's label.text-outline-color
: The colour of the outline around the element's label text.text-outline-width
: The size of the outline on label text.text-outline-opacity
: The opacity of the outline on label text.text-opacity
: The opacity of the label text, including its outline.font-family
: A comma-separated list of font names to use on the label text.font-style
: A CSS font style to be applied to the label text.font-weight
: A CSS font weight to be applied to the label text.font-size
: The size of the label text.visibility
: Whether the element is visible; can bevisible
orhidden
.opacity
: The opacity of the element.z-index
: A non-negative integer that specifies the z-ordering of the element. An element with a higherz-index
is put on top of an element with a lower value.width
: The element's width; the line width for edges or the horizontal size of a node.
Node properties
These properties apply only to nodes:
text-valign
: The vertical alignment of a label; may have valuetop
,center
, orbottom
.text-halign
: The vertical alignment of a label; may have valueleft
,center
, orright
.background-color
: The colour of the node's body.background-opacity
: The opacity level of the node's body.background-image
: The URL that points to the image that should be used as the node's background.border-color
: The colour of the node's border.border-width
: The size of the node's border.height
: The height of the node's body.shape
: The shape of the node's body; may berectangle
,roundrectangle
,ellipse
, ortriangle
.
Edge properties
These properties apply only to edges:
source-arrow-shape
: The shape of the edge's arrow on the source side; may betee
,triangle
,square
,circle
,diamond
, ornone
.source-arrow-color
: The colour of the edge's arrow on the source side.target-arrow-shape
: The shape of the edge's arrow on the target side; may betee
,triangle
,square
,circle
,diamond
, ornone
.target-arrow-color
: The colour of the edge's arrow on the target side.line-color
: The colour of the edge's line.
Core properties
These properties apply only to the core. You can use the special core
selector string to set these properties.
selection-box-color
: The background colour of the selection box used for drag selection.selection-box-opacity
: The opacity of the selection box.selection-box-border-color
: The colour of the border on the selection box.selection-box-border-width
: The size of the border on the selection box.panning-cursor
: The CSS cursor shown when the user pans the graph.
Mappers
In addition to specifying the value of a property outright, the developer may also use a mapper to dynamically specify the property value.
data()
specifies a direct mapping to an element's data field. For example, data(descr)
would map a property to the value in an element's descr
field in its data (i.e. ele.data("descr")
). This is useful for mapping to properties like label text content (the content
property).
mapData()
specifies a linear mapping to an element's data field. For example, data(weight, 0, 100, blue, red)
maps an element's weight to gradients between blue and red for weights between 0 and 100. An element with ele.data("weight") === 0
would be mapped to blue, for instance. Elements whose values fall outside of the specified range are mapped to the extremity values. In the previous example, an element with ele.data("weight") === -1
would be mapped to blue.
Events
Event object
Events passed to handler callbacks are jQuery-event-like objects. They have an additional field named cyTarget
, which indicates the element or core that first caused the event.
User input device events
These are normal browser events that you can bind to via Cytoscape.js. You can bind these events to the core and to collections.
mousedown
: when the mouse button is pressedmouseup
: when the mouse button is releasedclick
: after mousedown then mouseupmouseover
: when the cursor is put on top of the targetmouseout
: when the cursor is moved off of the targetmousemove
: when the cursor is moved somewhere on top of the targettouchstart
: when one or more fingers starts to touch the screentouchmove
: when one or more fingers are moved on the screentouchend
: when one or more fingers are removed from the screen
Collection events
These events are custom to Cytoscape.js. You can bind to these events for collections.
select
: when an element is selectedunselect
: when an element is unselectedlock
: when an element is lockedunlock
: when an element is unlockedgrab
: when an element is grabbed by the mouse cursor or a finger on a touch inputdrag
: when an element is grabbed and then movedfree
: when an element is freed (i.e. let go from being grabbed)position
: when an element changes positiondata
: when an element's data is changedbypass
: when an element's bypass is changedadd
: when an element is added to the graphremove
: when an element is removed from the graph
Graph events
These events are custom to Cytoscape.js, and they occur on the core.
layoutstart
: when a layout starts runninglayoutready
: when a layout has set positions for all the nodeslayoutstop
: when a layout has finished running completely or otherwise stopped runningload
: when a new graph is loaded via initialisation orcy.load()
ready
: when a new instance of Cytoscape.js is ready to be interacted withdone
: when a new instance of Cytoscape.js is ready to be interacted with and its initial layout has finished runningpan
: when the viewport is pannedzoom
: when the viewport is zoomed
Core
The core object is your interface to the Cytoscape.js visualisation. It is your entry point to Cytoscape.js: All of Cytoscape.js's features are accessed through this object.
Initialisation
Script includes
To use Cytoscape.js in your HTML document:
<script src="cytoscape.js"></script>
To use Cytoscape.js in Node.js:
var cytoscape = require('cytoscape');
Getting started
An instance of Cytoscape.js correeponds to a graph. You can create an instance as follows:
cytoscape({
container: someHtmlDomElement,
ready: function(){}
});
If you are running Cytoscape.js in Node.js or otherwise running it headlessly, you will not specify the container
option.
If you've included jQuery on a HTML document, you can alternatively initialise Cytoscape.js on a HTML DOM element using the traditional jQuery style:
$("#cy").cytoscape({ // for some div with id 'cy'
ready: function(){
// you can access the core object API through cy
},
...
});
This initialises Cytoscape.js and returns back to you your instance of jQuery. You can continue using jQuery functions, as usual for a jQuery plugin.
For example,
$("#cy").cytoscape(options)
.css("background", "red")
.css("border-color", "black"); // can use jquery functions on 'cy' div
Because this style doesn't give you access to the cy
object outside of the callback function, there is an option to get the cy
object from a jQuery selector.
$("#cy").cytoscape(options);
var cy = $("#cy").cytoscape("get"); // now we have a global reference to `cy`
The ready callback
All of your code that uses the core object API, i.e. through the cy
object in the examples above, must do so after the ready
callback function has executed. You can specify the ready
callback in the initialisation options, outlined in the following section.
Because the ready
event may occur before you can bind to the core, you can use this shortcut to spread your code among several JavaScript files without having to call a bunch of global functions in options.ready
.
// in foo.js
$(function(){ // on jquery ready
$("#cy").cytoscape(function(eventObject){ // on Cytoscape.js ready on the `cy` div
// this code executes when Cytoscape.js is ready even though we
// don't actually initialise Cytoscape.js on the `cy` div until
// bar.js is loaded
var cy = this; // `this` holds the reference to the core object
console.log("Ready, Freddie!");
});
});
// in bar.js (should be after foo.js in your js includes)
$(function(){ // on jquery ready
$("#cy").cytoscape(options);
});
Initialisation options
An instance of Cytoscape.js has a number of options that can be set on initialisation. They are outlined below.
$("#cy").cytoscape({
layout: { ... },
zoom: 1,
minZoom: 1e-50,
maxZoom: 1e50,
pan: { x: 0, y: 0 },
renderer: { ... },
style: { ... },
ready: function(evt){ ... },
elements: ...
});
layout : A plain object that specifies layout options. Which layout is initially run is specified by the name
field. Refer to a layout's documentation for the options it supports.
zoom : The initial zoom level of the graph. Make sure to disable viewport manipulation options, such as fit
, in your layout so that it is not overridden when the layout is applied. You can set minZoom and maxZoom to set restrictions on the zoom level.
pan : The initial panning position of the graph. Make sure to disable viewport manipulation options, such as fit
, in your layout so that it is not overridden when the layout is applied.
renderer : A plain object containing options for the renderer to be used. The name
field specifies which renderer is used. You need not specify anything for this option, unless you want to use a custom renderer.
style : The stylesheet used to style the document.
For example:
{
...
style: cytoscape.stylesheet()
.selector('node')
.css({
'background-color': 'red',
'border-color': '#ffff00'
})
.selector('edge')
.css({
'line-color': 'blue'
})
...
}
ready : A callback function that is called when Cytoscape.js is ready to be interacted with. You can not call functions on the cy
object before this function executes.
elements : An array of elements specified as plain objects.
For example:
{
...
elements: [
{
data: { id: 'foo' },
group: 'nodes'
},
{
data: { id: 'bar' },
group: 'nodes'
},
{
data: { weight: 100 }, // elided id => autogenerated id
group: 'nodes',
position: {
x: 100,
y: 100
},
classes: 'className1 className2',
selected: true,
selectable: true,
locked: true,
grabbable: true
},
{
data: { id: 'baz', source: 'foo', target: 'bar' },
group: 'edges'
}
]
...
}
You can alternatively specify separate arrays indexed in a object by the group names so you don't have to specify the group
property over and over for each element:
{
...
elements: {
nodes: [
{ data: { id: 'foo' } }, // NB no group specified
{ ... },
{ ... }
],
edges: [
{ ... }
]
}
...
}
Graph manipulation
- eleObj A plain object that specifies the element.
- eleObjs An array of elements specified by plain objects.
- eles A collection of elements.
Details
If plain element objects are used, then the same format used at initialisation must be followed. It is important to note that the group
attribute must be specified for plain objects, as this function can not infer whether the elements added are nodes or edges.
It is important to note that the positions of newly added nodes must be defined when calling cy.add()
. Nodes can not be placed in the graph without a valid position — otherwise they could not be displayed.
Examples
Add a node from a plain object.
cy.add({ group: "nodes", data: { id: "n0" } });
Add nodes and edges to the graph as plain objects:
// can use reference to eles later
var eles = cy.add([
{ group: "nodes", data: { id: "n0" }, position: { x: 100, y: 100 } },
{ group: "nodes", data: { id: "n1" }, position: { x: 200, y: 200 } },
{ group: "edges", data: { id: "e0", source: "n0", target: "n1" } }
]);
Add elements:
var n0 = cy.node("n1");
var n1 = cy.node("n2");
var e0 = cy.edge("e0");
n1.collection().add(n2).add(n3).remove(); // remove n0, n1, and e0
var n1e0 = n1.collection().add(e0);
cy.add(n0); // add a single element, n0
cy.add(n1e0); // add the collection of n1 and e0
- eles A collection of elements to remove.
- selector Elements matching this selector are removed.
Details
Though the elements specified to this function are removed from the graph, they may still exist in memory. However, some functions will not work on removed elements. For example, the neighborhood
function will fail for a removed element: An element outside of the context of the graph can not have a neighbourhood defined.
Examples
Remove an element:
var n0 = cy.nodes("#n0");
cy.remove(n0);
Remove a collection:
var collection = cy.elements("node[weight>50]");
cy.remove(collection);
Remove elements matching a selector:
cy.remove("node[weight>50]"); // remove nodes with weight greater than 50
- eleObjs An array of plain objects that specify the elements to load.
- load A callback function called when the graph has loaded.
- done A callback function called after the graph is loaded and just after the layout finishes.
Details
Note that eleObjs
can be specified as an array with each element specifying its group
, or alternatively, eleObjs
can be specified as a group
-indexed map, following the same format as in initialisation.
Examples
As an array:
cy.load([
{ data: { id: "n1" }, group: "nodes" },
{ data: { id: "n2" }, group: "nodes" },
{ data: { id: "e1", source: "n1", target: "n2" }, group: "edges" }
]);
As a group
-indexed map:
cy.load({
nodes: [
{ data: { id: "n1" } },
{ data: { id: "n2" } }
],
edges: [
{ data: { id: "e1", source: "n1", target: "n2" } }
]
});
With specified callbacks:
cy.load([ { data: { id: "n1" }, group: "nodes" } ], function(e){
console.log("cy loaded elements");
}, function(e){
console.log("cy laid out elements");
});
This is equivalent to:
cy.one("load", function(e){
console.log("cy loaded elements");
}).one("layoutdone", function(e){
console.log("cy laid out elements");
});
cy.load([ { data: { id: "n1" }, group: "nodes" } ]);
Details
This function is useful for building up collections.
Examples
Keep a collection of nodes that have been clicked:
var collection = cy.collection();
cy.nodes().live("click", function(){
collection = collection.add(this);
});
- selector The selector the elements should match.
- selector The selector the elements should match.
- selector The selector the nodes should match.
- selector The selector the edges should match.
- selector The selector the elements should match.
-
function(i, ele)
The filter function that returns true for elements that should be returned.
- – i The counter used for iteration over the elements in the graph.
- – ele The current element under consideration for filtering.
Details
If no elements in the graph match the selector, an empty collection is returned.
The function cy.$()
acts as an alias to cy.filter()
: It's just convenient to save you typing. It is analogous to the jQuery $
alias used to search the document
Examples
Get nodes with weight greater than 50:
var collection = cy.nodes("[weight>50]");
Get edges with source node n0
:
var collection = cy.edges("[source=n0]");
Get all nodes and edges with weight greater than 50:
var collection = cy.elements("[weight>50]");
collection = cy.filter("[weight>50]"); // works the same as the above line
Get nodes with weight greater than 50 with a filter function:
var collection = cy.filter(function(i, element){
if( element.isNode() && element.data("weight") > 50 ){
return true;
}
return false;
});
Viewport manipulation
- eles The collection to centre upon.
Details
If an empty collection or no collection is specified, then the graph is centred on all nodes and edges in the graph.
Examples
Centre the graph on node n0
:
var n0 = cy.node("n0");
cy.center(n0);
- eles The collection to fit to.
Details
If an empty collection or no collection is specified, then the graph is centred on all nodes and edges in the graph.
Examples
Centre the graph on node n0
:
var n0 = cy.node("n0");
cy.center(n0);
Details
This resets the viewport to the origin (0, 0) at zoom level 1.
Examples
cy.pan({ x: 100, y: 100 });
cy.zoom( 2 );
cy.reset();
- renderedPosition The rendered position to pan the graph to.
Details
This function pans the graph viewport origin to the specified rendered pixel position.
Examples
Pan the graph to (100, 100) rendered pixels.
cy.pan({
x: 100,
y: 100
});
console.log( cy.pan() ); // prints { x: 100, y: 100 }
- renderedPosition The rendered position vector to pan the graph by.
Details
This function shifts the viewport relatively by the specified position in rendered pixels. That is, specifying a shift of 100 to the right means a translation of 100 on-screen pixels to the right.
Examples
Pan the graph 100 pixels to the right.
cy.panBy({
x: 100,
y: 0
});
- bool A truthy value enables panning; a falsey value disables it.
- level The zoom level to set.
-
options
The options for zooming.
- – level The zoom level to set.
- – position The position about which to zoom.
- – renderedPosition The rendered position about which to zoom.
Details
The zoom level must be a positive number. Zoom levels that are not numbers are ignored; zoom levels that are numbers but outside of the range of valid zoom levels are considered to be the closest, valid zoom level.
When zooming about a point via cy.zoom( options )
, the options are defined as follows.
For zooming about a rendered position (i.e. a position on-screen):
var options = {
level: 2.0, // the zoom level
renderedPosition: { x: 100, y: 100 }
};
For zooming about a model position:
var options = {
level: 2.0, // the zoom level
position: { x: 500, y: 625 }
};
For obvious reasons, you can zoom about a position or a rendered position but not both. You should specify only one of options.position
or options.renderedPosition
.
Examples
Zoom in to factor 2
cy.zoom(2);
Zoom in to the minimum zoom factor
cy.zoom(0); // 0 is outside of the valid range and
// its closest valid level is the min
Zoom in to the maximum zoom factor
cy.zoom(1/0); // infinity is outside of the valid range and
// its closest valid level is the max
Zoom about a node
var pos = cy.nodes("#n0").position();
cy.zoom({
level: 2.5,
position: pos
});
- bool A truthy value enables zooming; a falsey value disables it.
- zoom The new minimum zoom level to use.
- zoom The new maximum zoom level to use.
Events
- events A space separated list of event names.
- selector A selector to specify elements for which the handler is triggered.
- data A plain object which is passed to the handler in the event object argument.
-
function(evt)
The handler function that is called when one of the specified events occurs.
- – evt The event object.
- eventsMap A map of event names to handler functions.
- selector A selector to specify elements for which the handler is triggered.
- data A plain object which is passed to the handler in the event object argument.
Examples
Bind to events that bubble up from elements matching the specified nodes
selector:
cy.on('click', 'nodes', { foo: 'bar' }, function(evt){
console.log( evt.data.foo ); // 'bar'
var node = this;
console.log( 'clicked ' + node.id() );
});
Bind to all click events that the core receives:
cy.on('click', function(event){
// cyTarget holds a reference to the originator
// of the event (core or element)
var evtTarget = event.cyTarget;
if( evtTarget === cy ){
console.log('click on background');
} else {
console.log('click on some element');
}
});
- events A space separated list of event names.
- data A plain object which is passed to the handler in the event object argument.
-
function(evt)
The handler function that is called when one of the specified events occurs.
- – evt The event object.
- eventsMap A map of event names to handler functions.
- data A plain object which is passed to the handler in the event object argument.
Examples
cy.one('click', 'node', function(){
console.log('click!');
});
cy.$('node').eq(0).trigger('click'); // click!
cy.$('node').eq(1).trigger('click'); // nothing b/c already clicked
- events A space separated list of event names.
- selector The same selector used to bind to the events.
- handler A reference to the handler function to remove.
- eventsMap A map of event names to handler functions to remove.
- selector The same selector used to bind to the events.
Examples
For all handlers:
cy.on("click", function(){ /* ... */ });
// unbind all click handlers, including the one above
cy.off("click");
For a particular handler:
var handler = function(){
console.log("called handler");
};
cy.on("click", handler);
var otherHandler = function(){
console.log("called other handler");
};
cy.on("click", otherHandler);
// just unbind handler
cy.off("click", handler);
- events A space separated list of event names to trigger.
- extraParams An array of additional parameters to pass to the handler.
Examples
cy.bind('click', function(evt, foo, bar){
console.log('click');
});
cy.trigger('click', ['foo', 'bar']);
Visuals
- options The layout options.
Options for included layouts
Several layouts are included with Cytoscape.js by default, and their options are described here with the default values specified. Note that you must set options.name
to the name of the layout to specify which one you want to run.
The random
layout:
options = {
ready: undefined, // callback on layoutready
stop: undefined, // callback on layoutstop
fit: true // whether to fit to viewport
};
The preset
layout puts nodes in the positions you specify manually:
options = {
fit: true, // whether to fit to viewport
ready: undefined, // callback on layoutready
stop: undefined, // callback on layoutstop
positions: undefined, // map of (node id) => (position obj)
zoom: undefined, // the zoom level to set (prob want fit = false if set)
pan: undefined // the pan level to set (prob want fit = false if set)
};
The grid
layout puts nodes in a well-spaced grid:
options = {
fit: true, // whether to fit the viewport to the graph
rows: undefined, // force num of rows in the grid
columns: undefined, // force num of cols in the grid
ready: undefined, // callback on layoutready
stop: undefined // callback on layoutstop
};
The arbor
layout uses a force-directed simulation:
options = {
liveUpdate: true, // whether to show the layout as it's running
ready: undefined, // callback on layoutready
stop: undefined, // callback on layoutstop
maxSimulationTime: 4000, // max length in ms to run the layout
fit: true, // fit to viewport
padding: [ 50, 50, 50, 50 ], // top, right, bottom, left
ungrabifyWhileSimulating: true, // so you can't drag nodes during layout
// forces used by arbor (use arbor default on undefined)
repulsion: undefined,
stiffness: undefined,
friction: undefined,
gravity: true,
fps: undefined,
precision: undefined,
// static numbers or functions that dynamically return what these
// values should be for each element
nodeMass: undefined,
edgeLength: undefined,
stepSize: 1, // size of timestep in simulation
// function that returns true if the system is stable to indicate
// that the layout can be stopped
stableEnergy: function( energy ){
var e = energy;
return (e.max <= 0.5) || (e.mean <= 0.3);
}
};
NB: You must reference the version of arbor.js
included with Cytoscape.js in the <head>
of your HTML document:
<head>
...
<script src="arbor.js"></script>
...
</head>
Arbor does some automatic path finding because it uses web workers, and so it must be included this way. Therefore, you can not combine arbor.js
with your other JavaScript files — as you probably would as a part of the minification of the scripts in your webapp.
The null
layout puts all nodes at (0, 0):
// The null layout has no options.
Examples
cy.layout({ name: 'grid' });
Details
You can use this function to gain access to the visual style after initialisation. This is useful if you need to change the entire stylesheet at runtime, though this is strongly not advised for most developers. It's akin to changing the CSS files you're using on a HTML document on-the-fly.
This example sets an entirely new style to the graph, specifying selectors and style properties:
cy.style()
.resetToDefault() // start a fresh default stylesheet
// and then define new styles
.selector('node:selected')
.css({ ... })
...
Collection
A collection contains a set of nodes and edges. Calling a function applies the function to all elements in the collection. When reading values from a collection, eles.data()
for example, the value of the first element in the collection is returned. This follows the jQuery convention. For example:
// assume graph:
// n1[weight = 10], n2[weight = 60], n3[weight = 90]
var weight = cy.nodes().data("weight"); // returns 10
You can insure that you're reading from the element you want by using a selector to narrow down the collection to one element (i.e. eles.size() === 1
) or the eles.eq()
function.
Graph manipulation
Details
This function removes the calling elements from the graph. The elements are not deleted — they still exist in memory — but they are no longer in the graph.
Examples
Remove selected elements:
cy.$(':selected').remove();
Details
This function puts back elements in the graph that have been removed. It will do nothing if the elements are already in the graph.
An element can not be restored if its ID is the same as an element already in the graph. You should specify an alternative ID for the element you want to add in that case.
Examples
// remove selected elements
var eles = cy.$(':selected').remove();
// ... then some time later put them back
eles.restore();
Data
- name The name of the field to get.
- name The name of the field to set.
- value The value to set for the field.
- obj The object containing name-value pairs to update data fields.
Details
The following fields are immutable:
id
: Theid
field is used to uniquely identify an element in the graph.source
&target
: These fields define an edge's relationship to nodes, and this relationship can not be changed after creation.parent
: Theparent
field is a reserved field for the future implementation of compound nodes.
Examples
var n1 = cy.$('#n1');
// set the weight field in data
n1.data('weight', 75);
// set several fields at once
n1.data({
foo: 'some value',
bar: 'another value',
baz: 'yet another value'
});
var weight = n1.data('weight');
- names A space-separated list of fields to delete.
Details
The following data fields are immutable, and so they can not be removed:
id
: Theid
field is used to uniquely identify an element in the graph.source
&target
: These fields define an edge's relationship to nodes, and this relationship can not be changed after creation.parent
: Theparent
field is a reserved field for the future implementation of compound nodes.
Details
The group strings are nodes
for nodes and edges
for edges. In general, you should be using ele.isEdge()
and ele.isNode()
instead of ele.group()
.
Metadata
Details
Degree : For a node, the degree is the number of edge connections it has. Each time a node is referenced as source
or target
of an edge in the graph counts as an edge connection.
Indegree : For a node, the indegree is the number of incoming edge connections it has. Each time a node is referred to as target
of an edge in the graph counts as an incoming edge connection.
Outdegree : For a node, the outdegree is the number of outgoing edge connections it has. Each time a node is referred to as source
of an edge in the graph counts as an outgoing edge connection.
Total degree : For a set of nodes, the the total degree is the total number of edge connections to nodes in the set.
Position & dimensions
- dimension The position dimension to get.
- dimension The position dimension to set.
- value The value to set to the dimension.
- pos An object specifying name-value pairs representing dimensions to set.
Details
A position has two fields, x
and y
, that can take on numerical values. Non-numerical values are ignored.
Examples
// get x for n1
var x = cy.$('#n1').position('x');
// get the whole position for n2
var pos = cy.$('#n2').position();
// set y for n1
cy.$('#n1').position('y', 100);
// set multiple
cy.$('#n2').position({
x: 123,
y: 456
});
-
fn(i, ele)
A callback function that returns the position to set for each element.
- – i The index of the element when iterating over the elements in the collection.
- – ele The element being iterated over for which the function should return a position to set.
- dimension The position dimension to get.
- dimension The position dimension to set.
- value The value to set to the dimension.
- pos An object specifying name-value pairs representing dimensions to set.
Selection
Events
- events A space separated list of event names.
- data A plain object which is passed to the handler in the event object argument.
-
function(evt)
The handler function that is called when one of the specified events occurs.
- – evt The event object.
- eventsMap A map of event names to handler functions.
- selector A selector to specify elements for which the handler is triggered.
- data A plain object which is passed to the handler in the event object argument.
Defails
In the handler function, this
references the element that triggered the event.
Examples
cy.on('click', function(evt){
console.log( 'clicked ' + this.id() );
});
- events A space separated list of event names.
- data A plain object which is passed to the handler in the event object argument.
-
function(evt)
The handler function that is called when one of the specified events occurs.
- – evt The event object.
- eventsMap A map of event names to handler functions.
- data A plain object which is passed to the handler in the event object argument.
Details
For each event specified to this function, the handler function is triggered once per element. This is useful for one-off events that occur on each element once.
Examples
cy.$('node').one('click', function(){
var ele = this;
console.log('clicked ' + ele.id());
});
cy.$('#n1').trigger('click'); // clicked n1
cy.$('#n1').trigger('click'); // nothing
cy.$('#n2').trigger('click'); // clicked n2
- events A space separated list of event names.
- data A plain object which is passed to the handler in the event object argument.
-
function(evt)
The handler function that is called when one of the specified events occurs.
- – evt The event object.
- eventsMap A map of event names to handler functions.
- data A plain object which is passed to the handler in the event object argument.
Details
For each event specified to this function, the handler function is triggered once. This is useful for one-off events that occur on just one element in the collection.
Examples
cy.$('node').once('click', function(){
var ele = this;
console.log('clicked ' + ele.id());
});
cy.$('#n1').trigger('click'); // clicked n1
cy.$('#n1').trigger('click'); // nothing
cy.$('#n2').trigger('click'); // nothing
- events A space separated list of event names.
- handler A reference to the handler function to remove.
- eventsMap A map of event names to handler functions to remove.
- selector The same selector used to bind to the events.
Examples
var n1 = cy.$('#n1');
var handler = function(){ console.log('click') };
// bind
n1.on('click', handler);
// bind some other handler
n1.on('click', function(){
console.log('some other handler');
});
n1.trigger('click'); // 'click' & 'some other handler'
// unbind the renferenced handler
n1.off('click', handler);
n1.trigger('click'); // some other handler
// unbind all click handlers (including unnamed handler)
n1.off('click');
- events A space separated list of event names to trigger.
- extraParams An array of additional parameters to pass to the handler.
Examples
var n1 = cy.$('#n1');
n1.on('click', function(){
console.log('click!!');
});
n1.trigger('click'); // click!!
Style
- name The name of the visual style property to get.
- name The name of the property to set.
- value The value to set to the visual style property.
- props An object with name-value pairs representing properties to set on the elements.
Details
You should use this function very sparingly, because it overrides the style of an element, despite the state and classes that it has. In general, it's much better to specify a better stylesheet at initialisation that reflects your application state rather than programmatically modifying style.
Only defined visual style properties are supported.
If you would like to remove a particular overridden style property, set null
to it.
- name The name of the visual style property to get.
- classes A space-separated list of class names to add to the elements.
- classes A space-separated list of class names to remove from the elements.
- classes A space-separated list of class names to toggle on the elements.
- toggle Instead of automatically toggling, adds the classes on `true` or removes them on `false`.
- className The name of the class to test for.
Animation
-
props
An object containing the properties to animate.
- – position A position to which the elements will be animated.
- – css An object containing name-value pairs of style properties to animate.
-
options
An object containing animation options.
- – duration The duration of the animation in milliseconds.
- – queue A boolean indicating whether to queue the animation.
- – complete A function to call when the animation is done.
- – step A function to call each time the animation steps.
Examples
cy.nodes().animate({
position: { x: 100, y: 100 },
css: { backgroundColor: 'red' }
}, {
duration: 1000
});
- duration How long the delay should be in milliseconds.
- complete A function to call when the delay is complete.
- clearQueue A boolean, indicating whether the queue of animations should be emptied.
- jumpToEnd A boolean, indicating whether the currently-running animations should jump to their ends rather than just stopping midway.
Comparison
- eles The other elements to compare to.
- eles The other elements to compare to.
- eles The other elements to compare to.
- selector The selector to match against.
- selector The selector to match against.
Iteration
Details
Note that as a non-functional alternative, you may read eles.length
instead of eles.size()
. The two are interchangeable.
-
function(i, ele)
The function executed each iteration.
- – i The index of the element in the collection.
- – ele The element at the current index.
Examples
cy.elements().each(function(i, ele){
console.log( ele.id() + ' is ' + ( ele.selected() ? 'selected' : 'not selected' ) );
});
- index The index of the element to get.
- start An integer that specifies where to start the selection (The first element has an index of 0). Use negative numbers to select from the end of an array.
- end An integer that specifies where to end the selection. If omitted, all elements from the start position and to the end of the array will be selected. Use negative numbers to select from the end of an array.
Traversing
- selector An optional selector that is used to filter the resultant collection.
- selector An optional selector that is used to filter the resultant collection.
- selector An optional selector that is used to filter the resultant collection.
Details
The neighbourhood returned by this function is a bit different than the traditional definition of a "neighbourhood": This returned neighbourhood includes the edges connecting the collection to the neighbourhood. This gives you more flexibility.
An open neighbourhood is one that does not include the original set of elements. If unspecified, a neighbourhood is open by default.
A closed neighbourhood is one that does include the original set of elements.
- selector An optional selector that is used to filter the resultant collection.
- selector An optional selector that is used to filter the resultant collection.
- selector An optional selector that is used to filter the resultant collection.
- selector An optional selector that is used to filter the resultant collection.
- selector An optional selector that is used to filter the resultant collection.
- selector An optional selector that is used to filter the resultant collection.
Details
Two edges are said to be parallel if they connect the same two nodes. That is,
edge1.source() === edge2.source() && edge1.target() === edge2.target()
oredge1.source() === edge2.target() && edge1.target() === edge2.source()
.
- selector An optional selector that is used to filter the resultant collection.
Details
Two edges are said to be codirected if they connect the same two nodes in the same direction. That is, edge1.source() === edge2.source() && edge1.target() === edge2.target()
.
Building & filtering
- eles The elements to add.
- eles The elements that will not be in the resultant collection.
- selector Elements matching this selector will not be in the resultant collection.
- eles The elements to intersect with.
- selector The selector to match against.
-
function(i, ele)
The filter function that returns true for elements to include.
- – i The index of the current element being considered.
- – ele The element being considered.
- selector The selector to match against.
- selector The selector to match against.
Extensions
API
The extensions API is very simple, following this format:
cytoscape( type, name, extension );
The value of type
can take on the following values:
core
: The extension adds a core function.collection
: The extension adds a collection function.layout
: The extension registers a layout prototype.renderer
: The extension registers a renderer prototype.
The name
argument indicates the name of the extension, which should be a single word in lower case.
Functions
Functions should be chainable, unless they need to return some other value. To make a function chainable, make sure to return this;
at the end of your function.
Here is an example collection function:
cytoscape('collection', 'forEach', function( fn ){
for( var i = 0; i < this.length; i++ ){
fn.apply( this[i], [ i, this[i] ] );
}
return this; // chainability
});
Layouts
For an example layout, please refer to the null layout source code. The layout just sets each node to position (0, 0), and it is well documented.
Renderers
For an example renderer, please refer to the canvas renderer. If you're interested in writing a custom renderer for Cytoscape.js, please send an email to Max.