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

1

7

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.

Ferreby answered 26/4, 2021 at 20:34 Comment(2)
Could you post a minimal code snippet that shows the problem?Dumb
sure, I'll update itFerreby
D
9

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

Dumb answered 27/4, 2021 at 8:26 Comment(7)
I thought about this solution but in my network almost every node has a degree greater than 1Ferreby
@Ferreby How is that a problem? The title is shown over the edge, not the node.Dumb
Ah, my apologizes, you are right. It seems to solve my problem, thank you!Ferreby
Glad I could help (:Dumb
Did you get this to work? I have tried sending title param to add_edge() and am not seeing anything show up when clicking on the edge.Preciosa
It works, I just tested this snippet again with Python 3.10 and pyvis 0.3.1Dumb
It works in at least Firefox and Edge. Have you looked at the nx.html file to see if it mentions your edge label?Dumb

© 2022 - 2024 — McMap. All rights reserved.