In a network graph, how do I highlight the network components when hovering over them?

I have made a network graph. Now I want to add 3 functionalities -

  • when hovering over an edge, it should highlight the nodes connected with that edge

  • when hovering over a node, it should highlight all the nodes and edges connected to that node

  • when selecting a sub-area in the network (by dragging the mouse), instead of zooming into the graph, it should highlight the nodes and edges in that selected sub-area

How do I do these? I found this pen, but I donโ€™t know how to adapt it to Python do this in an automated manner for every node in the graph.


This is my code:

import plotly.graph_objs as go
import networkx as nx
from plotly.offline import download_plotlyjs, init_notebook_mode,  iplot, plot

init_notebook_mode(connected=True)

#create graph G
G = nx.karate_club_graph()

# adjust node size according to degree, etc
d = nx.degree(G)
node_sizes = []
for i in d:
    _, value = i
    node_sizes.append(3*value+5)

#get a x,y position for each node  
pos = nx.circular_layout(G)

#add a pos attribute to each node
for node in G.nodes:
    G.nodes[node]['pos'] = list(pos[node])

pos=nx.get_node_attributes(G,'pos')


dmin=1
ncenter=0
for n in pos:
    x,y=pos[n]
    d=(x-0.5)**2+(y-0.5)**2
    if d<dmin:
        ncenter=n
        dmin=d

p=nx.single_source_shortest_path_length(G,ncenter)

#Create Edges
edge_trace = go.Scatter(
    x=[],
    y=[],
    line=dict(width=0.5,color='#888'),
    hoverinfo='none',
    mode='lines')

edge_trace['line'] = dict(width=0.5,color='#FF0000')

for edge in G.edges():
    x0, y0 = G.node[edge[0]]['pos']
    x1, y1 = G.node[edge[1]]['pos']
    edge_trace['x'] += tuple([x0, x1, None])
    edge_trace['y'] += tuple([y0, y1, None])

node_trace = go.Scatter(
    x=[],
    y=[],
    text=[],
    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='Viridis',
        reversescale=True,
        color=[],
        size=node_sizes,
        colorbar=dict(
            thickness=15,
            title='Node Connections',
            xanchor='left',
            titleside='right'
        ),  
        line=dict(width=2)))

for node in G.nodes():
    x, y = G.node[node]['pos']
    node_trace['x'] += tuple([x])
    node_trace['y'] += tuple([y])

#add color to node points
for node, adjacencies in enumerate(G.adjacency()):
    node_trace['marker']['color']+=tuple([len(adjacencies[1])])
    node_info = 'Name: ' + str(adjacencies[0]) + '<br># of connections: '+str(len(adjacencies[1]))
    node_trace['text']+=tuple([node_info])
    
f = go.Figure(data=[edge_trace, node_trace],
              layout=go.Layout(
                title='<br>Network Graph of Karate Club',
                titlefont=dict(size=16),
                showlegend=False,
                hovermode='closest',
                width=880,
                height=800,
                margin=dict(b=20,l=5,r=5,t=40),
                annotations=[ dict(
                    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)
              )
             )

iplot(f)

Hi @kristada619,

This should be possible from Python using either:

  1. The FigureWidget class if you need this to work in the Jupyter Notebook. See https://plot.ly/python/#chart-events for a bunch of examples on the interactive features.
  2. Use Dash if you want this to work in a standalone web app. See https://dash.plot.ly/interactive-graphing for info on plot callbacks.

Hope that helps.
-Jon