I'm plotting a network from a pandas df using Networkx and pyvis. The edge weights are working in Networkx, but are not refelected in pyvis. Here is my code example:
import numpy as np; np.random.seed(0)
import pandas as pd
import networkx as nx
from pyvis.network import Network
file = r"test.xlsx"
df = pd.read_excel(file, engine='openpyxl')
node1 | node2 | node1_len | node1_size | edge_weight | |
---|---|---|---|---|---|
0 | AAAAAAAAAA | AAAAAAAAAB | 10 | 20 | 9.0 |
1 | AAAAAAAAAA | AAAAABBBBB | 10 | 20 | 0.5 |
2 | AAAAAAAAAB | AAAAAAAAAA | 10 | 40 | 9.0 |
3 | AAAAAAAAAB | AAAAABBBBB | 10 | 40 | 0.6 |
4 | AAAAABBBBB | AAAAAAAAAA | 10 | 60 | 0.5 |
5 | AAAAABBBBB | AAAAAAAAAB | 10 | 60 | 0.6 |
#generate a Networkx graph
G = nx.from_pandas_edgelist(df, source = 'node1', target = 'node2', edge_attr = 'edge_weight', create_using = nx.Graph())
edges = G.edges.data()
#node positions
pos = nx.kamada_kawai_layout(G)
#setting up attributes
node_size = {}
#edge_width = {}
for index, row in df.iterrows():
node_size[row['node1']] = row['node1_size']
#edge_width[(row['node1'], row['node2'])] = row['edge_weight']
nx.set_node_attributes(G, node_size, 'size')
#nx.set_edge_attributes(G, edge_weight, 'ratio')
#draw networkx graph
edge_width = [e[2]['edge_weight'] for e in edges]
nx.draw(G, pos=pos, with_labels=True) # draw nodes (and edges!)
nx.draw_networkx_edges(G, pos=pos, width=edge_width) # paint over edges with specified width.
#Graph visualization using Pyvis
net = Network(width='1900px', height='900px', bgcolor='#222222', font_color='white')
net.repulsion()
net.from_nx(G)
for e in edges:
print(e[2]['edge_weight'])
net.add_edge(e[0],e[1], value=e[2]['edge_weight'])
net.show('test.html')`
Notes:
The code lines where I'm trying to add the edge weights to the pyvis net object have no effect.
for e in edges:
print(e[2]['edge_weight'])
net.add_edge(e[0],e[1], value=e[2]['edge_weight'])
I tried various approaches, e.g., modifying the edge attributes in various ways in the networkx G object - like I did for the node sizes (see the commented-out lines in the '#setting up attributes' section), but didn't manage to change the edge width in pyvis.