Adding node labels to bokeh network plots

旧街凉风 提交于 2019-12-03 11:36:27

I guess you mean interactive labels for the nodes, something I also wanted to do. To achieve this, you need to modify a couple of lines:

hover = HoverTool(tooltips=[("Name:", "@name")])
plot.add_tools(hover, TapTool(), BoxSelectTool(), WheelZoomTool())
...
graph_renderer.inspection_policy = NodesAndLinkedEdges()

Then modify the data source for the nodes:

graph_renderer.node_renderer.data_source.data['name'] = [name1, ... ,nameN]

(the data source already exists; it's a dictionary for which the only key is 'index', a numbered list of nodes. Thus you can add more keys that reference lists of the same length - such as a list of names - and these lists can be accessed via '@key')

I found @SergioLucero's answer too incomplete to answer the question, the code sample is not working.

However, with code and answer created by @ifearthenight (from this question: Lining up labels with the nodes on a Bokeh figure generated from a NetworkX graph) I was able to produce a working example.

from bokeh.io import show, output_notebook
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource, LabelSet
from bokeh.models.graphs import from_networkx
output_notebook()

G = nx.karate_club_graph()

plot = figure(title="Karate Club Graph", tools="", x_range=(-1.5, 1.5),
          y_range=(-1.5, 1.5), toolbar_location=None)
graph = from_networkx(G, nx.spring_layout)
plot.renderers.append(graph)

x, y = zip(*graph.layout_provider.graph_layout.values())
node_labels = nx.get_node_attributes(G, 'club')
source = ColumnDataSource({'x': x, 'y': y,
                           'club': [node_labels[i] for i in range(len(x))]})
labels = LabelSet(x='x', y='y', text='club', source=source,
                  background_fill_color='white')

plot.renderers.append(labels)
show(plot)

Hot topic!! I think I just got it. They may be more pythonic ways, but what I did was

  1. Create a DataSource with the relevant labels
  2. Retrieve positions from the graph using pos = nx.circular_layout(G)
  3. add these positions to my Datasource
  4. Create a LabelSet from the positions and the source

Leonardo, you are missing the line where G gets created. I took the karate_club_graph and this works for me:

from bokeh.models import ColumnDataSource
pos = nx.circular_layout(G)
x,y=zip(*pos.values())

source = ColumnDataSource({'x':x,'y':y,'kid':['Joe %d' %ix for ix in range(len(x))]})
labels = LabelSet(x='x', y='y', text='kid', source=source)

plot.renderers.append(labels)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!