Search code examples
pythonnetworkxbokeh

Bokeh Different Hovers for source and target nodes


I create a network graph with Bokeh networkx from a df:

df = pd.DataFrame('source': [1,2,3], 'target': ['a', 'b', 'c], 'name': ['a1', 'b2', 'c3'])

with source nodes from column source and target nodes from column target

Is there any way to show up hovers of

HoverTool(tooltips = [("SOURCE", "$source"), ("NAME", "$name")])

for 'source' nodes and

HoverTool(tooltips = [("TARGET", "$target")])

for target nodes?

My code is as following:

import pandas as pd
from bokeh.io import show
import networkx as nx
from bokeh.models import Plot, MultiLine, Circle
from bokeh.models.graphs import from_networkx
net_graph = networkx.from_pandas_edgelist(df, 'source', 'target', 'name')
for index, row in df.iterrows():
    net_graph.nodes[row['source']]['source_hover'] = row['source']
    net_graph.nodes[row['source']]['name hover'] = row['name']
    net_graph.nodes[row['target']]['target hover'] = row['target']
graph_plot = Plot(plot_width = 800, plot_height = 600, x_range = Range1d(-1.1, 1.1), y_range = Range1d(-1.1, 1.1))
graph_setup = from_networkx(net_graph, nx.spring_layout, scale = 1, center = (0, 0))
graph_plot.add_tools(HoverTool(renderers=[graph_setup], tooltips=[("SOURCE", "@source_hover"), ("NAME", "@name_hover")]))
graph_plot.add_tools(HoverTool(renderers=[graph_setup], tooltips=[("TARGET", "@target_hover")]))
graph_setup.node_renderer.glyph = Circle(size = 20, fill_color = 'red')
graph_setup.edge_renderer.glyph = MultiLine(line_color = "grey", line_alpha = 0.8, line_width = 1)
graph_plot.renderers.append(graph_setup)
show(graph_plot)

Solution

  • you could change renderers below by your graph or if you have different glyphs you could add p, p2, etc. I cannot help very well because your intention is unclear and we don't have your codes.

    p.add_tools(HoverTool(renderers=[], tooltips=[("SOURCE", "$source"), ("NAME", "$name")])
    p.add_tools(HoverTool(renderers=[], tooltips=[("TARGET", "$target")])
    

    renderers=[] part will help you to do that. renderers are basically your lines/bars etc. for above you've got Multiline (which have list of renderers) and Circle. so basically for circle graph just use renderers[]

    for example for circle first give a name:

    circlename = Circle(size = 20, fill_color = 'red')
    

    and in hover tool add renderers=[circlename]

    MultiLine part is little bit tricky. You've got multiple lines. so you have to give names to all of them. You basically could use dictinary and for loop to give names. and could detetermine in renderers part like above. You could check it out from here