3.3. Producing Dynamic Graphs with PyVis#

PyVis is a powerful Python library that is capable of outputting an HTML file which contains the data and JavaScript necessary for users to view and engage with network data. It has a fairly large community and is well-supported. One of its largest advantages over NetworkX and Matplotlib is in the dynamic nature of the graphs.

Dynamic graphs, or those that can be manipulated by a user in some capacity, are better suited than static graphs for networks that a large or more complex.

There are other libraries for doing similar steps as laid out here. Bokeh is a suitable alternative. The main issue with Bokeh is that it has a steep learning curve and, while it certainly offers greater flexibility and customization options than PyVis, it can be challenging for those newer to Python. As we will see, you can produce quality, dynamic network graphs with PyVis in just a few lines of Python code. For this reason, I am opting to focus on PyVis in this section.

You can install PyVis via pip by running in the command line:

pip install pyvis

This should install PyVis on your system.

3.3.1. The Basics of PyVis#

Once you have installed PyVis, you will want to import the Network class. We can do so with the following line.

from pyvis.network import Network

The Network class holds all of the data that will be used to create the graph. Since we are working within a Jupyter Notebook, we will want to set the keyword argument notebook to True. This will ensure that when we create our network graph, it will not only output as an HTML file, but also load within the notebook.

We can create a Network object and load it into memory with the following command.

net = Network(notebook=True)
Local cdn resources have problems on chrome/safari when used in jupyter-notebook. 

Again, we will work with the same toy data here.

rels = [
    
    ["Fred", "George"],
    ["Harry", "Rita"],
    ["Fred", "Ginny"],
    ["Tom", "Ginny"],
    ["Harry", "Ginny"]
    
]

In PyVis, we want to create each node in the graph individually and then populate the edge between the two nodes in the relationship. Therefore, we will want to iterate over each relationship with a for loop. We will use the .add_node method for each node in the graph and the .add_edge() method to create an edge between the two nodes.

for rel in rels:
    source, dest = rel
    net.add_node(source)
    net.add_node(dest)
    net.add_edge(source, dest)

Once we have populated the Network class with all our date, we can visualize it with theo method .show(). This will take a single argument, a string that will be the file created.

net.save_graph("simple_graph.html")
from IPython.display import HTML
HTML(filename="simple_graph.html")

In the graph above, try to interact with the data. You will notice that you can drag-and-drop nodes. You can zoom in and out in the graph. This is a good demonstration of the power PyVis has over NetworkX and Matplotlib.