I’m trying to display edge weights of Networkx graph while plotting using plotly. There is a problem in displaying the edge weights as edge labels while hovering over edges of the resulting plot.
Code:
import numpy as np
import networkx as nx
import plotly.graph_objects as go
from pprint import pprint
from collections import OrderedDict
from matplotlib import pyplot as plt
def get_edge_trace(G):
edge_x = []
edge_y = []
etext = [f'weight{w}' for w in list(nx.get_edge_attributes(G, 'diameter').values())]
for edge in G.edges():
x0, y0 = G.nodes[edge[0]]['pos']
x1, y1 = G.nodes[edge[1]]['pos']
edge_x.append(x0)
edge_x.append(x1)
edge_x.append(None)
edge_y.append(y0)
edge_y.append(y1)
edge_y.append(None)
edge_trace = go.Scatter(
x=edge_x, y=edge_y,
line=dict(width=0.5, color='#888'),
marker=dict(color='rgb(125,125,125)', size=1),
text=etext,
hoverinfo='text',
mode='lines' # lines
)
return edge_trace
def get_node_trace(G):
node_x = []
node_y = []
for node in G.nodes():
x, y = G.nodes[node]['pos']
node_x.append(x)
node_y.append(y)
node_trace = go.Scatter(
x=node_x, y=node_y,
mode='markers',
hoverinfo='text',
marker=dict(
showscale=True,
# colorscale options
# 'Greys' | 'YlGnBu' | 'Greens' | 'YlOrRd' | 'Bluered' | 'RdBu' |
# 'Reds' | 'Blues' | 'Picnic' | 'Rainbow' | 'Portland' | 'Jet' |
# 'Hot' | 'Blackbody' | 'Earth' | 'Electric' | 'Viridis' |
colorscale='YlGnBu',
reversescale=True,
color=[],
size=10,
colorbar=dict(
thickness=15,
title='Node Connections',
xanchor='left',
titleside='right'
),
line_width=2))
return node_trace
if __name__ == '__main__':
tail = [1, 2, 3]
head = [2, 3, 4]
xpos = [0, 1, 2, 3]
ypos = [0, 0, 0, 0]
w = [1, 2, 3]
xpos_ypos = [(x, y) for x, y in zip(xpos, ypos)]
ed_ls = [(x, y) for x, y in zip(tail, head)]
G = nx.OrderedGraph()
G.add_edges_from(ed_ls)
pos = OrderedDict(zip(G.nodes, xpos_ypos))
edge_w = OrderedDict(zip(G.edges, w))
nx.draw(G, pos=pos, with_labels=True)
nx.set_node_attributes(G, pos, 'pos')
nx.set_edge_attributes(G, edge_w, 'weight')
plt.show()
# convert to plotly graph
edge_trace = get_edge_trace(G)
node_trace = get_node_trace(G)
pprint(np.array(nx.get_edge_attributes(G, 'diameter').values()))
pprint(edge_trace)
pprint(node_trace)
fig = go.Figure(data=[edge_trace, node_trace],
layout=go.Layout(
title='<br>Network graph made with Python',
titlefont_size=16,
showlegend=False,
hovermode='closest',
margin=dict(b=20, l=5, r=5, t=40),
annotations=[dict(
text="Python code: <a href='https://plot.ly/ipython-notebooks/network-graphs/'> https://plot.ly/ipython-notebooks/network-graphs/</a>",
showarrow=False,
xref="paper", yref="paper",
x=0.005, y=-0.002)],
xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
yaxis=dict(showgrid=False, zeroline=False, showticklabels=False))
)
fig.write_html('plot.html', auto_open=True)
The edge weights aren’t displayed for some reason while hovering over edges. I’ve added edge text n get_edge_trace function.
Could someone help me out?