Pyvis
Pyvis
Release 0.1.3.1
1 Contents: 3
1.1 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 License . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.5 Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.6 Indices and tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Index 21
i
ii
pyvis Documentation, Release 0.1.3.1
Contents 1
pyvis Documentation, Release 0.1.3.1
2 Contents
CHAPTER 1
Contents:
1.1 Installation
Or you can download an archive of the project here. To install, unpack it and run the following in the top-level
directory:
1.2 Introduction
The goal of this project is to build a python based approach to constructing and visualizing network graphs in the same
space. A pyvis network can be customized on a per node or per edge basis. Nodes can be given colors, sizes, labels,
and other metadata. Each graph can be interacted with, allowing the dragging, hovering, and selection of nodes and
edges. Each graph’s layout algorithm can be tweaked as well to allow experimentation with rendering of larger graphs.
Pyvis is built around the amazing VisJS library.
1.3 Tutorial
The pyvis library is meant for quick generation of visual network graphs with minimal python code. It is designed as
a wrapper around the popular Javascript visJS library found at this link.
3
pyvis Documentation, Release 0.1.3.1
Here, the first parameter to the add_node method is the desired ID to give the Node. This can be a string or a numeric.
The label argument is the string that will be visibly attached to the node in the final visualization. If no label argument
is specified then the node id will be used as a label.
Note: network.Network.add_nodes() accepts any iterable as long as the contents are strings or numerics
A call to add_node() supports various node properties that can be set individually. All of these properties can
be found here, courtesy of VisJS. For the direct Python translation of these attributes, reference the network.
Network.add_node() docs.
Note: Through no fault of pyvis, some of the attributes in the VisJS documentation do not work as expected, or at all.
Pyvis can translate into the JavaScript elements for VisJS but after that it’s up to VisJS!
When using the network.Network.add_nodes() method optional keyword arguments can be passed in to add
properties to these nodes as well. The valid properties in this case are
4 Chapter 1. Contents:
pyvis Documentation, Release 0.1.3.1
Each of these keyword args must be the same length as the nodes parameter to the method.
Example:
>>> g = Network()
>>> g.add_nodes([1,2,3], value=[10, 100, 400],
title=['I am node 1', 'node 2 here', 'and im node 3'],
x=[21.4, 54.2, 11.2],
y=[100.2, 23.54, 32.1],
label=['NODE 1', 'NODE 2', 'NODE 3'],
color=['#00ff1e', '#162347', '#dd4b39'])
Note: If you mouse over each node you will see that the title of a node attribute is responsible for rendering data
on mouse hover. You can add HTML in your title string and it will be rendered as such.
Note: The color attribute can also be a plain HTML color like red or blue. You can also specify the full rgba
specification if needed. The VisJS documentation has more details.
Detailed optional argument documentation for nodes are in the network.Network.add_node() method docu-
mentation.
1.3.6 Edges
Assuming the network’s nodes exist, the edges can then be added according to node id’s
>>> net.add_node(0, label='a')
>>> net.add_node(1, label='b')
>>> net.add_edge(0, 1)
An easy way to visualize and construct pyvis networks is to use Networkx and use pyvis’s built-in networkx helper
method to translate the graph. Note that the Networkx node properties with the same names as those consumed by
pyvis (e.g., title) are translated directly to the correspondingly-named pyvis node attributes.
>>> from pyvis.network import Network
>>> import networkx as nx
>>> nx_graph = nx.cycle_graph(10)
>>> nx_graph.nodes[1]['title'] = 'Number 1'
>>> nx_graph.nodes[1]['group'] = 1
>>> nx_graph.nodes[3]['title'] = 'I belong to a different group!'
>>> nx_graph.nodes[3]['group'] = 10
(continues on next page)
1.3. Tutorial 5
pyvis Documentation, Release 0.1.3.1
1.3.8 Visualization
The displaying of a graph is achieved by a single method call on network.Network.show() after the underlying
network is constructed. The interactive visualization is presented as a static HTML file.
>>> net.toggle_physics(True)
>>> net.show('mygraph.html')
Note: Triggering the toggle_physics() method allows for more fluid graph interactions
sources = got_data['Source']
targets = got_data['Target']
weights = got_data['Weight']
for e in edge_data:
src = e[0]
dst = e[1]
w = e[2]
neighbor_map = got_net.get_adj_list()
6 Chapter 1. Contents:
pyvis Documentation, Release 0.1.3.1
got_net.show("gameofthrones.html")
If you want to try out the above code, the csv data source can be downloaded
Note: The title attribute of each node is responsible for rendering data on node hover.
You also have the option of supplying your visualization with a UI used to dynamically alter some of the settings
pertaining to your network. This could be useful for finding the most optimal parameters to your graph’s physics and
layout function.
>>> net.show_buttons(filter_=['physics'])
Note: You can copy/paste the output from the generate options button in the above UI into network.Network.
set_options() to finalize your results from experimentation with the settings.
You can highlight a node and its neighboring edges and nodes by clicking on the node or choosing the drop down
above when select_menu option is set as True. The selected node and its neighbours will be highlighted while the rest
of the network is greyed out.
You can also filter on certain objects of the network like nodes and edges. You can activate this feature by passing
filter_menu option as True. With this option turned on, you can build a query choosing edges or nodes, then choosing
the attribute to filter on and finally a value or multiple values to filter. When you filter on nodes, the selected node
will be highlighted and rest of the network will be hidden. If the selected nodes are connected the edges will also be
highlighted. When you filter on edges, the nodes connecting them will be highlighted along with the edges.
Note: You can use these two features independently and can also combine them to get a customized view of the
network
1.3. Tutorial 7
pyvis Documentation, Release 0.1.3.1
Pyvis supports Jupyter notebook embedding through the use of the network.Network() constructor. The network
instance must be “prepped” during instantiation by supplying the notebook=True kwarg. Example:
Note: while using notebook in chrome browser, to render the graph, pass additional kwarg ‘cdn_resources’ as
‘remote’ or ‘inline’
8 Chapter 1. Contents:
pyvis Documentation, Release 0.1.3.1
1.4 License
1.5 Documentation
>>> nt = Network()
Parameters
• arrowStrikethrough (bool) – When false, the edge stops at the arrow. This can be
useful if you have thick lines and you want the arrow to end in a point. Middle arrows are
not affected by this.
1.4. License 9
pyvis Documentation, Release 0.1.3.1
• from (str or num) – Edges are between two nodes, one to and one from. This is
where you define the from node. You have to supply the corresponding node ID. This
naturally only applies to individual edges.
• hidden (bool) – When true, the edge is not drawn. It is part still part of the physics
simulation however!
• physics (bool) – When true, the edge is part of the physics simulation. When false, it
will not act as a spring.
• title (str) – The title is shown in a pop-up when the mouse moves over the edge.
• to (str or num) – Edges are between two nodes, one to and one from. This is where
you define the to node. You have to supply the corresponding node ID. This naturally only
applies to individual edges.
• value (num) – When a value is set, the edges’ width will be scaled using the options in
the scaling object defined above.
• width (num) – The width of the edge. If value is set, this is not used.
add_edges(edges)
This method serves to add multiple edges between existing nodes in the network instance. Adding of the
edges is done based off of the IDs of the nodes. Order does not matter unless dealing with a directed graph.
Parameters edges – A list of tuples, each tuple consists of source of edge, edge destination
and and optional width.
add_node(n_id, label=None, shape=’dot’, color=’#97c2fc’, **options)
This method adds a node to the network, given a mandatory node ID. Node labels default to node ids if no
label is specified during the call.
Parameters
• n_id (str or int) – The id of the node. The id is mandatory for nodes and they have
to be unique. This should obviously be set per node, not globally.
• label (str or int) – The label is the piece of text shown in or under the node,
depending on the shape.
• borderWidth (num (optional)) – The width of the border of the node.
• borderWidthSelected (num (optional)) – The width of the border of the node
when it is selected. When undefined, the borderWidth * 2 is used.
• brokenImage (str (optional)) – When the shape is set to image or circularImage,
this option can be an URL to a backup image in case the URL supplied in the image option
cannot be resolved.
• group (str (optional)) – When not undefined, the node will belong to the defined
group. Styling information of that group will apply to this node. Node specific styling
overrides group styling.
• hidden (bool (optional)) – When true, the node will not be shown. It will still be
part of the physics simulation though!
10 Chapter 1. Contents:
pyvis Documentation, Release 0.1.3.1
• image (str (optional)) – When the shape is set to image or circularImage, this
option should be the URL to an image. If the image cannot be found, the brokenImage
option can be used.
• labelHighlightBold (bool (optional)) – Determines whether or not the label
becomes bold when the node is selected.
• level (num (optional)) – When using the hierarchical layout, the level determines
where the node is going to be positioned.
• mass (num (optional)) – The barnesHut physics model (which is enabled by de-
fault) is based on an inverted gravity model. By increasing the mass of a node, you increase
it’s repulsion. Values lower than 1 are not recommended.
• physics (bool (optional)) – When false, the node is not part of the physics sim-
ulation. It will not move except for from manual dragging.
• shape (str (optional)) – The shape defines what the node looks like. There are
two types of nodes. One type has the label inside of it and the other type has the label
underneath it. The types with the label inside of it are: ellipse, circle, database, box, text.
The ones with the label outside of it are: image, circularImage, diamond, dot, star, triangle,
triangleDown, square and icon.
• size (num (optional)) – The size is used to determine the size of node shapes that
do not have the label inside of them. These shapes are: image, circularImage, diamond,
dot, star, triangle, triangleDown, square and icon.
• title (str or html element (optional)) – 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.
• value (num (optional)) – When a value is set, the nodes will be scaled using the
options in the scaling object defined above.
• x (num (optional)) – This gives a node an initial x position. When using the hi-
erarchical layout, either the x or y position is set by the layout engine depending on the
type of view. The other value remains untouched. When using stabilization, the stabilized
position may be different from the initial one. To lock the node to that position use the
physics or fixed options.
• y (num (optional)) – This gives a node an initial y position. When using the hierar-
chical layout,either the x or y position is set by the layout engine depending on the type of
view. The other value remains untouched. When using stabilization, the stabilized posi-
tion may be different from the initial one. To lock the node to that position use the physics
or fixed options.
add_nodes(nodes, **kwargs)
This method adds multiple nodes to the network from a list. Default behavior uses values of ‘nodes’ for
node ID and node label properties. You can also specify other lists of properties to go along each node.
Example:
>>> g = net.Network()
>>> g.add_nodes([1, 2, 3], size=[2, 4, 6], title=["n1", "n2", "n3"])
>>> g.nodes
>>> [{'id': 1, 'label': 1, 'shape': 'dot', 'size': 2, 'title': 'n1'},
Output:
1.5. Documentation 11
pyvis Documentation, Release 0.1.3.1
12 Chapter 1. Contents:
pyvis Documentation, Release 0.1.3.1
Parameters dot (dot file) – The path of the dotfile being converted.
1.5. Documentation 13
pyvis Documentation, Release 0.1.3.1
Usage:
get_node(n_id)
Lookup node by ID and return it.
Parameters n_id – The ID given to the node.
Returns dict containing node properties
get_nodes()
This method returns an iterable list of node ids
Returns list
hrepulsion(node_distance=120, central_gravity=0.0, spring_length=100, spring_strength=0.01,
damping=0.09)
This model is based on the repulsion solver but the levels are taken into account and the forces are normal-
ized.
Parameters
• node_distance (int) – This is the range of influence for the repulsion.
• central_gravity – The gravity attractor to pull the entire network to the center.
• spring_length – The rest length of the edges
• spring_strength – The strong the edges springs are
• damping – A value ranging from 0 to 1 of how much of the velocity from the previous
physics simulation iteration carries over to the next iteration.
:type central_gravity float :type spring_length: int :type spring_strength: float :type damping: float
inherit_edge_colors(status)
Edges take on the color of the node they are coming from.
Parameters status (bool) – True if edges should adopt color coming from.
neighbors(node)
Given a node id, return the set of neighbors of this particular node.
Parameters node (str or int) – The node to get the neighbors from
Returns set
num_edges()
Return number of edges
Returns int
num_nodes()
Return number of nodes
Returns int
prep_notebook(custom_template=False, custom_template_path=None)
Loads the template data into the template attribute of the network. This should be done in a jupyter
notebook environment before showing the network.
Example:
>>> net.prep_notebook()
>>> net.show("nb.html")
14 Chapter 1. Contents:
pyvis Documentation, Release 0.1.3.1
Parameters path (string) – the relative path pointing to a template html file
1.5. Documentation 15
pyvis Documentation, Release 0.1.3.1
• status (bool) – When set to True, the widgets will be shown. Default is set to False.
• filter (bool or list:) – Only include widgets specified by filter_. Valid options:
True (gives all widgets)
List of nodes, edges, layout, interaction, manipulation, physics, selection, renderer.
toggle_drag_nodes(status)
Toggles the dragging of the nodes in the network.
Parameters status (bool) – When set to True, the nodes can be dragged around in the net-
work. Default is set to True.
toggle_hide_edges_on_drag(status)
Displays or hides edges while dragging the network. This makes panning of the network easy.
Parameters status (bool) – True if edges should be hidden on drag
toggle_hide_nodes_on_drag(status)
Displays or hides nodes while dragging the network. This makes panning of the network easy.
Parameters status (bool) – When set to True, the nodes will hide on drag. Default is set to
False.
toggle_physics(status)
Toggles physics simulation
Parameters status (bool) – When False, nodes are not part of the physics simulation. They
will not move except for from manual dragging. Default is set to True.
toggle_stabilization(status)
Toggles the stablization of the network.
Parameters status (bool) – Default is set to True.
write_html(name, local=True, notebook=False, open_browser=False)
This method gets the data structures supporting the nodes, edges, and options and updates the template to
write the HTML holding the visualization.
To work with the old local methods local is being depricated, but not removed. :type name_html: str
@param name: name of the file to save the graph as. @param local: Depricated parameter. Used to be
used to determine how the graph needs deploy. Has been removed in favor of using the class cdn_resources
instead. @param notebook: If true, this object will return the iframe document for use in juptyer notebook.
@param open_browser: If true, will open a web browser with the generated graph.
class pyvis.options.Configure(enabled=False, filter_=None)
Handles the HTML part of the canvas and generates an interactive option editor with filtering.
class pyvis.options.EdgeOptions
This is where the construction of the edges’ options takes place. So far, the edge smoothness can be switched
through this object as well as the edge color’s inheritance.
class Color
The color object contains the color information of the edge in every situation. When the edge only needs
a single color value like ‘rgb(120,32,14)’, ‘#ffffff’ or ‘red’ can be supplied instead of an object.
class Smooth
When the edges are made to be smooth, the edges are drawn as a dynamic quadratic bezier curve. The
drawing of these curves takes longer than that of the straight curves but it looks better. There is a difference
between dynamic smooth curves and static smooth curves. The dynamic smooth curves have an invisible
support node that takes part in the physics simulation. If there are a lot of edges, another kind of smooth
than dynamic would be better for performance.
16 Chapter 1. Contents:
pyvis Documentation, Release 0.1.3.1
inherit_colors(status)
Whether or not to inherit colors from the source node. If this is set to from then the edge will take the color
of the source node. If it is set to to then the color will be that of the destination node.
Note: If set to True then the from behavior is adopted and vice versa.
toggle_smoothness(smooth_type)
Change smooth option for edges. When using dynamic, the edges will have an invisible support node
guiding the shape. This node is part of the physics simulation,
Parameters smooth_type (str) – Possible options are dynamic, continuous, discrete, diag-
onalCross, straightCross, horizontal, vertical, curvedCW, curvedCCW, cubicBezier
class pyvis.options.Interaction
Used for all user interaction with the network. Handles mouse and touch events as well as the navigation buttons
and the popups.
class pyvis.options.Layout(randomSeed=None, improvedLayout=True)
Acts as the camera that looks on the canvas. Does the animation, zooming and focusing.
set_edge_minimization(status)
Method for reducing whitespace. Can be used alone or together with block shifting. Enabling block
shifting will usually speed up the layout process. Each node will try to move along its free axis to reduce
the total length of it’s edges. This is mainly for the initial layout. If you enable physics, they layout will
be determined by the physics. This will greatly speed up the stabilization time
set_separation(distance)
The distance between the different levels.
set_tree_spacing(distance)
Distance between different trees (independent networks). This is only for the initial layout. If you enable
physics, the repulsion model will denote the distance between the trees.
class pyvis.options.Options(layout=None)
Represents the global options of the network. This object consists of indiviual sub-objects that map to VisJS’s
modules of:
• configure
• layout
• interaction
• physics
• edges
The JSON representation of this object is directly passed in to the VisJS framework. In the future this can be
expanded to completely mimic the structure VisJS can expect.
set(new_options)
This method should accept a JSON string and replace its internal options structure with the given argument
after parsing it. In practice, this method should be called after using the browser to experiment with
different physics and layout options, using the generated JSON options structure that is spit out from the
front end to serve as input to this method as a string.
Parameters new_options (str) – The JSON like string of the options that will override.
1.5. Documentation 17
pyvis Documentation, Release 0.1.3.1
• genindex
• modindex
• search
• Glossary
18 Chapter 1. Contents:
Python Module Index
p
pyvis.network, 9
pyvis.options, 16
19
pyvis Documentation, Release 0.1.3.1
A inherit_edge_colors() (pyvis.network.Network
add_edge() (pyvis.network.Network method), 9 method), 14
add_edges() (pyvis.network.Network method), 10 Interaction (class in pyvis.options), 17
add_node() (pyvis.network.Network method), 10
add_nodes() (pyvis.network.Network method), 11 L
Layout (class in pyvis.options), 17
B
barnes_hut() (pyvis.network.Network method), 12 N
neighbors() (pyvis.network.Network method), 14
C Network (class in pyvis.network), 9
Configure (class in pyvis.options), 16 num_edges() (pyvis.network.Network method), 14
num_nodes() (pyvis.network.Network method), 14
E
EdgeOptions (class in pyvis.options), 16 O
EdgeOptions.Color (class in pyvis.options), 16 Options (class in pyvis.options), 17
EdgeOptions.Smooth (class in pyvis.options), 16
F P
prep_notebook() (pyvis.network.Network method),
force_atlas_2based() (pyvis.network.Network
14
method), 12
pyvis.network (module), 9
from_DOT() (pyvis.network.Network method), 12
pyvis.options (module), 16
from_nx() (pyvis.network.Network method), 13
G R
generate_html() (pyvis.network.Network method), repulsion() (pyvis.network.Network method), 15
13
get_adj_list() (pyvis.network.Network method), S
13 save_graph() (pyvis.network.Network method), 15
get_edges() (pyvis.network.Network method), 13 set() (pyvis.options.Options method), 17
get_network_data() (pyvis.network.Network set_edge_minimization() (pyvis.options.Layout
method), 13 method), 17
get_node() (pyvis.network.Network method), 14 set_edge_smooth() (pyvis.network.Network
get_nodes() (pyvis.network.Network method), 14 method), 15
set_options() (pyvis.network.Network method), 15
H set_separation() (pyvis.options.Layout method),
hrepulsion() (pyvis.network.Network method), 14 17
set_template() (pyvis.network.Network method),
I 15
inherit_colors() (pyvis.options.EdgeOptions set_template_dir() (pyvis.network.Network
method), 16 method), 15
21
pyvis Documentation, Release 0.1.3.1
set_tree_spacing() (pyvis.options.Layout
method), 17
show() (pyvis.network.Network method), 15
show_buttons() (pyvis.network.Network method),
15
T
toggle_drag_nodes() (pyvis.network.Network
method), 16
toggle_hide_edges_on_drag()
(pyvis.network.Network method), 16
toggle_hide_nodes_on_drag()
(pyvis.network.Network method), 16
toggle_physics() (pyvis.network.Network
method), 16
toggle_smoothness() (pyvis.options.EdgeOptions
method), 17
toggle_stabilization() (pyvis.network.Network
method), 16
W
write_html() (pyvis.network.Network method), 16
22 Index