Search code examples
networkxgraph-visualizationpyvis

How to Highlight any given path in pyvis network graph visualization?


I'm working on a project in which first i had to detect the shortest path in a huge network graph using a-star algorithm followed by visualizing the same graph using pyvis network. However in this pyvis network the path that I've calculated should be highlighted as shortest path.

eg: consider this code for game of thrones character network

from pyvis.network import Network
import pandas as pd

got_net = Network(height='750px', width='100%', bgcolor='#222222', font_color='white')

# set the physics layout of the network
got_net.barnes_hut()
got_data = pd.read_csv('https://www.macalester.edu/~abeverid/data/stormofswords.csv')

sources = got_data['Source']
targets = got_data['Target']
weights = got_data['Weight']

edge_data = zip(sources, targets, weights)

for e in edge_data:
    src = e[0]
    dst = e[1]
    w = e[2]

    got_net.add_node(src, src, title=src)
    got_net.add_node(dst, dst, title=dst)
    got_net.add_edge(src, dst, value=w)

neighbor_map = got_net.get_adj_list()

# add neighbor data to node hover data
for node in got_net.nodes:
    node['title'] += ' Neighbors:<br>' + '<br>'.join(neighbor_map[node['id']])
    node['value'] = len(neighbor_map[node['id']])

got_net.show('gameofthrones.html')

Graph visualization

Now how do i highlight a specific path in this graph? i've gone through the documentation but there isn't anything similar


Solution

  • Here's an example using NetworkX to create the graph and gravis to visualize it. I had to use a different URL, hope it's the same data. I've used the weight as edge widths and colored some with large weights. Alternatively you can calculate a shortest path between two nodes of interest and then color that path or assign edge widths so it stands out.

    Disclosure: I'm the author of gravis. I don't know if the same can be achieved with pyvis, but since I know that gravis supports the requirements well, I provided this solution and hope it's useful.

    import gravis as gv
    import networkx as nx
    import pandas as pd
    
    url = 'https://raw.githubusercontent.com/pupimvictor/NetworkOfThrones/master/stormofswords.csv'
    got_data = pd.read_csv(url)
    
    g = nx.Graph()
    for i, (source, target, weight) in got_data.iterrows():
        width = weight/10
        g.add_edge(source, target, size=width, color='blue' if width > 3 else 'black')
        
    gv.d3(g)
    

    Edit: Here's the output if you use this code inside a Jupyter notebook. You can also use a regular Python interpreter and display the plot inside a browser window that pops up with fig = gv.d3(g) followed by fig.display().

    enter image description here