The world’s leading publication for data science, AI, and ML professionals.

Making network graphs interactive with Python and Pyvis.

The easy way to superb graphs.

Image by author.
Image by author.

For a while, I and others in the Streamlit community [1] have been seeking a tool to render interactive graphs, but until now this has been something only a few can achieve. This can be due to the fact that a level of expertise with javascript is required, something that many Streamlit users may want to avoid, as this is the promise of the project, deploy beautiful web apps from python, no javascript required!! (of course, mastering javascript is a big plus for making awesome streamlit apps).

Recently I found Pyvis after a few weeks looking for an alternative to other javascript based libraries used to make graphs interactive. I liked pyvis a lot and wanted to share in this post some tips I’ve learned. But if you want to see by yourself, check the documentation page [2]:

Interactive network visualizations – pyvis 0.1.3.1 documentation

The rest of this post is as follows: First, I will show a super simple example to do a small 3 nodes net. Second, I show how to fix the positions of nodes and how to preserve the shape of the graph of a molecule. The third case is devoted to building a network with Networkx. Finally, I show a Streamlit app working with Pyvis.

1. Simple graph example.

I will start with a simple example, creating a Network object and adding 3 nodes (method _addnode) labeled 1, 2, and 3 with two edges (method _addedge) [1–2] and [2–3]. In order to deploy the graph (for example in a Jupyter or Colab environment) pyvis "translates" the python code to html+javascript with the show method. Calling g.show(‘example.html’) writes to disk the html file which can be rendered with display:

and here is the result,

Image by author. Simple example for Pyvis 🚀 .
Image by author. Simple example for Pyvis 🚀 .

And that’s all easy, isn’t it? This basic recipe will be used in the following. I did a small function _showgraph() to do the display in a single step, as you could see in the snippets below. You can find this and all the code in a Colab notebook in the github repo at the bottom 🙌 .

2. Molecules as graphs.

The next case is something I figured out that could be achieved, combining pyvis with the chemoinformatics library RDKit 🤓 [3]. I assume this is not of general interest, so I will avoid the process to build up the molecule, and instead, I will present just the resulting nodes and connectivity information of the atoms. This is shown here for caffeine molecule ☕️.

Image by author. Caffeine molecule
Image by author. Caffeine molecule

As I want to preserve its shape, first I need the coordinates of the atoms, but also some very specific physics options. Let me explain in a simple way how this is accomplished: as there are 14 atoms, I did a loop running on each atom number, assigning nodes with the _addnode method. For each node, I gave the atom symbol, and Cartesian __ coordinates from three separated lists (which I got from RDKit preprocessing) named respectively _id_s, _x_s and _y_s:

for atomo in range(14): 
    g3.add_node(atomo,label=ids[atomo],
    x=int(100*xs[atomo]),y=int(100*ys[atomo]),
    physics=True,size=30)

(xs and ys are arbitrarily multiplied by 100 just to make the graph more manageable)

The full snippet is hosted with ❤️ 🙂 where you can see also the physics options:

And this is what results, pretty much acceptable I think:

Image by author. 2D representation converted to an interactive graph with Pyvis 😎  .
Image by author. 2D representation converted to an interactive graph with Pyvis 😎 .

This can be used chiefly for presentations to catch eye attention or to design chemistry-oriented web pages. But other uses could be envisioned as well.

3. Now, some karate moves.

If you are familiar with Networkx [4], you should know that it is very popular because this library is easy to use and well documented, but as far as I know, it lacks this feature of making the graph interactive. Fortunately, Pyvis accepts graph objects from Networkx beautifully. Networkx has prebuilt the Zachary’s Karate Club graph [5], where you have 34 members of the club, being 0 and 33 the President and the Sensei which have a conflict, and they separate the club in two groups based on influence among members. Below is shown the piece of code needed for this graph in pyvis. First, we got G with the graph from Networkx. Then we build the pyvis object g4, and __ metho_d fromnx is used to get the graph into pyvis… as simple as that:

Here I must highlight the _showbuttons method in line 8, which is used to deploy the physics options, allowing the user to change interactively the way the nodes interact with each other as if they were connected by springs and having other physical interactions. That makes the dynamics of the graph look more "natural" and visually is a joy.

Image by author. Graph of the Zachary's Karate Club dataset generated using Networkx in Pyvis 🤛.
Image by author. Graph of the Zachary’s Karate Club dataset generated using Networkx in Pyvis 🤛.

Of course, there are other ways to make graphs interactive, using advanced libraries, but in general, they are more complex. The simplicity offered by pyvis is something that is appreciated.

4. Deploy on streamlit.

Finally, I show how these dynamic graphs look in a Streamlit web app. I am not going to discuss how to do the app, I let that as homework to the reader.

hint: you can see the github repo below 😏

image by author. Pyvis running in Streamlit 🔥 .
image by author. Pyvis running in Streamlit 🔥 .

What to do now..

  • If you want, you can play with the web app here:

https://share.streamlit.io/napoles-uach/streamlit_network/main/app.py

  • If you liked it, please star the github repo 🌟

https://github.com/napoles-uach/streamlit_network

  • The code snippets presented here are part of a Colab Notebook that you can find here:

https://github.com/napoles-uach/streamlit_network/blob/main/pyvis_sample.ipynb

Thanks for reading!!

Help me to continue creating content like this by using the following link to become a Medium Member. For only $5/mo, you will get full access to every story on Medium and also that will support me with $2.27, thanks!

https://medium.com/@jnapoles/membership

Join Medium with my referral link – JOSÉ MANUEL NÁPOLES DUARTE


Links cited:

[1] Streamlit

[2] Interactive network visualizations – pyvis 0.1.3.1 documentation

[3] RDKit

[4] NetworkX – NetworkX documentation

[5] Zachary’s karate club


Related Articles