Search code examples
pythonnetwork-programminggraphgraph-visualizationpyvis

Is it possible to display weight of edges of a network using PyVis and Python?


I've read the documentation and I did add edges with attribute weight but the weight of edges is not displayed on the plot and it is not displayed when I hover a curses onto the link between two nodes. Is it possible to display weight?

Code snippet (source: https://pyvis.readthedocs.io/en/latest/tutorial.html#networkx-integration):

from pyvis.network import Network
import networkx as nx

nx_graph = nx.cycle_graph(10)
nx_graph.nodes[1]['title'] = 'Number 1'
nx_graph.nodes[1]['group'] = 1
nx_graph.nodes[3]['title'] = 'I belong to a different group!'
nx_graph.nodes[3]['group'] = 10
nx_graph.add_node(20, size=20, title='couple', group=2)
nx_graph.add_node(21, size=15, title='couple', group=2)
nx_graph.add_edge(20, 21, weight=5)
nx_graph.add_node(25, size=25, label='lonely', title='lonely node', group=3)
nt = Network('500px', '500px')
# populates the nodes and edges data structures
nt.from_nx(nx_graph)
nt.show('nx.html')

Result: result of the snippet

How can I display the weight of an edge? In this example there is a weight of edge of nodes 20 and 21.


Solution

  • You can supply a title= argument to add_edge() which will display a tooltip with the label if you hover over the edge:

    from pyvis.network import Network
    
    g = Network()
    g.add_node(0)
    g.add_node(1)
    g.add_edge(0, 1, value=5, title="42")  # weight 42
    g.show('nx.html')
    

    enter image description here

    Source