How can we plot a network graph, using pyvis, in a browser?

956 views Asked by At

When I run the code below, I get this message but no network graph is displayed.

Warning: When cdn_resources is 'local' jupyter notebook has issues displaying graphics on chrome/safari. Use cdn_resources='in_line' or cdn_resources='remote' if you have issues viewing graphics in a notebook. example.html

import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt


data = [{'Circuit': 'html','Description':1, 'Duration':10.2, 'Source':'Westchester', 'Destination':'Davie', 'Picklist':1000, 'Postlist':50000.2}, 
       {'Circuit': 'html', 'Description':2, 'Duration':12.1, 'Source':'Westchester', 'Destination':'Davie', 'Picklist':3000, 'Postlist':40000.1},
       {'Circuit': 'html', 'Description':3, 'Duration':11.3, 'Source':'Westchester', 'Destination':'Davie', 'Picklist':7000, 'Postlist':50000.2}, 
       {'Circuit': 'html', 'Description':3, 'Duration':8.1, 'Source':'West', 'Destination':'San Bernardino', 'Picklist':3000, 'Postlist':40000.0},
       {'Circuit': '.net', 'Description':4, 'Duration':6.2, 'Source':'Queens', 'Destination':'San Bernardino', 'Picklist':5000, 'Postlist':6000.1}, 
       {'Circuit': '.net', 'Description':3, 'Duration':20.1, 'Source':'Queens', 'Destination':'Los Angeles', 'Picklist':5000, 'Postlist':4000.1},
       {'Circuit': '.net', 'Description':2, 'Duration':15.5, 'Source':'Brooklyn', 'Destination':'San Francisco', 'Picklist':5000, 'Postlist':9000.3},
       {'Circuit': '.net', 'Description':4, 'Duration':7.7, 'Source':'Brooklyn', 'Destination':'Davie', 'Picklist':6000, 'Postlist':10000},
       {'Circuit': '.net', 'Description':4, 'Duration':7.7, 'Source':'Los Angeles', 'Destination':'Westchester', 'Picklist':6000, 'Postlist':10000},
       {'Circuit': '.net', 'Description':4, 'Duration':7.7, 'Source':'San Berdarnino', 'Destination':'Westchester', 'Picklist':6000, 'Postlist':10000}]
df = pd.DataFrame(data)
df

import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt

G = nx.from_pandas_edgelist(df, source='Source', target='Destination', edge_attr='Picklist')

from pyvis.network import Network
net = Network(notebook=True)
net.from_nx(G)
net.show('example.html')

If I add this code below, I get a static graph, but I really want the dynamic graph using the code above.

G = nx.from_pandas_edgelist(pandas_df, source = "StorageLocation", target = "StorageType", edge_attr = "Value", create_using = nx.Graph())
plt.figure(figsize=(15,12))

nx.draw(G, with_labels=True, node_color='skyblue', edge_cmap=plt.cm.Blues)
plt.show()
2

There are 2 answers

0
ASH On BEST ANSWER

Definitely helpful! Thanks for getting me pointed in the right direction. This is what ultimately worked for me.

import pandas as pd
import numpy as np
import networkx as nx
from IPython.display import display, HTML

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)

from pyvis.network import Network
net = Network(notebook=True)
net.from_nx(G)
#net = Network()

net.from_nx(G)

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

The problem was, although I could see the graph in a Jupyter notebook, I could not see the graph in a Databricks notebook. Now the code works in a Databricks notebook, in Firefox/Mozilla. Thanks again!!

0
Wayne On

Not sure specifically what you are asking since it tells you what to do and how to do it.

"Use cdn_resources='in_line' or cdn_resources='remote' if you have issues viewing graphics in a notebook. example.html"

Here is how to see an adaptation of your code work in a browser interactively (you can scroll and zoom), not as a static image, without installing anything on your own system.

Go to here and press the 'launch binder' badge at the bottom. The session will spin up. (If it seems to take too long for the system to 'start up', try this link in case of issues.) When the session comes up open a new notebook and in that notebook run the following code in a new cell:

%pip install pyvis

When that completes running, restart the kernel.

Now you are read to try and run the adapted version of your code.

Adapted version of your code to run there, based on that advice and example here:

import pandas as pd
import numpy as np
import networkx as nx
from IPython.display import display, HTML
import matplotlib.pyplot as plt


data = [{'Circuit': 'html','Description':1, 'Duration':10.2, 'Source':'Westchester', 'Destination':'Davie', 'Picklist':1000, 'Postlist':50000.2}, 
       {'Circuit': 'html', 'Description':2, 'Duration':12.1, 'Source':'Westchester', 'Destination':'Davie', 'Picklist':3000, 'Postlist':40000.1},
       {'Circuit': 'html', 'Description':3, 'Duration':11.3, 'Source':'Westchester', 'Destination':'Davie', 'Picklist':7000, 'Postlist':50000.2}, 
       {'Circuit': 'html', 'Description':3, 'Duration':8.1, 'Source':'West', 'Destination':'San Bernardino', 'Picklist':3000, 'Postlist':40000.0},
       {'Circuit': '.net', 'Description':4, 'Duration':6.2, 'Source':'Queens', 'Destination':'San Bernardino', 'Picklist':5000, 'Postlist':6000.1}, 
       {'Circuit': '.net', 'Description':3, 'Duration':20.1, 'Source':'Queens', 'Destination':'Los Angeles', 'Picklist':5000, 'Postlist':4000.1},
       {'Circuit': '.net', 'Description':2, 'Duration':15.5, 'Source':'Brooklyn', 'Destination':'San Francisco', 'Picklist':5000, 'Postlist':9000.3},
       {'Circuit': '.net', 'Description':4, 'Duration':7.7, 'Source':'Brooklyn', 'Destination':'Davie', 'Picklist':6000, 'Postlist':10000},
       {'Circuit': '.net', 'Description':4, 'Duration':7.7, 'Source':'Los Angeles', 'Destination':'Westchester', 'Picklist':6000, 'Postlist':10000},
       {'Circuit': '.net', 'Description':4, 'Duration':7.7, 'Source':'San Berdarnino', 'Destination':'Westchester', 'Picklist':6000, 'Postlist':10000}]
df = pd.DataFrame(data)


G = nx.from_pandas_edgelist(df, source='Source', target='Destination', edge_attr='Picklist')

from pyvis.network import Network
g = Network(notebook=True, cdn_resources='remote')
g.from_nx(G)
display(HTML(g.generate_html()))

Result after restarting and running code a few times:

enter image description here

If it doesn't show the graph after about 30 seconds, restart the kernel and run the cell again. My first time it took a couple repeats of that cycle and then it displayed the network consistently; however, I was installing via the Jupyter terminal and maybe not waiting & restarting properly. Plus make sure you only have one cell in your session trying to display a pyvis graph at a time! (Clear output from any one before trying another.) Your mileage may vary. It would probably work better if it was built specifically to run this package so that it had the package properly installed form the get-go. I think that pressing the 'launch binder' badge at the bottom of the page here should give you such a session, however, the developer has left out matplotlib for some inexplicable reason (at the time I tried %pip install matplotlib run in the notebook in such launched sessions errored with a version issue), and I didn't feel like making a special repo with everything specified properly for the mybinder service in the configuration file. (If it seems to hang, you can try here, similarly to my directions with the default repo above.)


But what if you REALLY just want to display the resulting interactive graph in your local web browser without Jupyter running?

Part of doing what I did above was to get to a point I had good pyvis-related code that I could use to try & see if what it generates can be taken and used to display the graph interactively later, without Jupyter running. It turns out it can!
Here is how to take the example above that is working in Jupyter and move it to running directly in a web browser as an independent HTML file. This may be more along the lines of what you want; however, I needed to get to this point first, and hopefully, by describing the full pathway to making your code example work and getting to just the HTML, you'll see how to plug this in to what you are doing and where you are working.

If you look at the code above, you'll see part of what it does is generate HTML that gets displayed in Jupyter. You can get that HTML yourself. There's at least a couple of ways to get the generated HTML. Probably most direct, you can have pyvis generate the HTML with a command like net.save_graph("networkx-pyvis.html") (see Ash's answer with code that uses this approach.) In the case when using Jupyter in the steps, you also generate HTML and you can use Jupyter and Python alone to collect that and then paste it into your favorite code editor and save that text file on your local machine with the .html extension. Then when you run your browser and point it at the .html file, it will display the interactive plot!

Step-by-step how to get the HTML via Jupyter and Python (see Ash's answer for the net.save_graph() route) after running the code above:

  • Make a new cell after you have the plot displayed at least once. You can clear the output from that cell if you like or not, it shouldn't matter. In the new cell, add the following code:
c = g.generate_html()
print(c)
  • That code will print the HTML you need. You can either select that code in the running Jupyter notebook and copy it to your clipboard and paste it into your favorite code text editor running on your machine and save it as my_html.html on your local machine. Or, add the the line %store c >my_html.html after those two lines in a new cell (or in the same cell after the above two lines) and run that line (if you added it below those two lines, run the entire cell). It will save the .html file in the Jupyter session. If you save it in the session, you need to right-click on the file in the file navigator pane on the left and download it to your machine. (Optionally, you can verify making the HTML worked without downloading it from the session first by double clicking on the file my_html.html in the file navigation pane on the left of the Jupyter session and then pressing the 'Trust HTML' button in the upper left in the Jupyter window that comes up. After you press the 'Trust HTML' button, the HTML code will be run as HTML by JupyterLab and the graph displayed.

  • With the my_html.html saved on you local machine, you are ready to open it with your local browser. On my Mac, I right click on the saved file and choose to 'Open with ...' and select Chrome. Your path will vary depending on your system. Now you have HTML code generated by pyvis that is displaying in your browser interactively (it scrolls & zooms) without needing Jupyter currently running.

Result in a browser window (added to answer later and so doesn't perfectly match result above):

enter image description here