3.4. NetworkX and PyVis#

While this works, we don’t have all the advantages that NetworkX afforded us. PyVis, it is important to note, while useful, is primarily a wrapper for producing JavaScript graphs. It is not as robust as NetworkX when it comes to handling and querying complex network relationships. We cannot generate, for example, metrics for things like centrality. For these reasons, it is best to combine the best of NetworkX and PyVis by first passing your network data to NetworkX, creating the graph, and then passing the NetworkX graph to PyVis for conversion to an interactive graph.

import networkx as nx

Just as we did in the previous section, we will create a NetworkX nx.Graph() and populate it with our relationships.

G = nx.Graph()
rels = [
    
    ["Fred", "George"],
    ["Harry", "Rita"],
    ["Fred", "Ginny"],
    ["Tom", "Ginny"],
    ["Harry", "Ginny"],
    ["Harry", "George"],
    ["Frank", "Ginny"],
    ["Marge", "Rita"],
    ["Fred", "Rita"]
    
]
G.add_edges_from(rels)

Now that we have our NetworkX Graph, we can create a PyVis Network class.

net = Network()

Using the from_nx() method, which will take a single argument, our NetworkX Graph, or G.

net.from_nx(G)

With the data now populated, we can save and view our PyVis Network.

net.save_graph("networkx-pyvis.html")
HTML(filename="networkx-pyvis.html")

Notice that our graph is rendered precisely just as it had been with NetworkX and Matplotlib, but now that same data is dynamic. In other words, we were able to leverage the best of NetworkX and PyVis with this approach.