简体   繁体   中英

Drag nodes using Networkx and Bokeh

I'm using bokeh with networkx to visualize a graph like this:( https://docs.bokeh.org/en/latest/docs/user_guide/graph.html#node-and-edge-attributes )

And I'm wondering if it's possible to drag the nodes. I've tried things like PointDrawTool ( https://docs.bokeh.org/en/latest/docs/user_guide/tools.html#pointdrawtool ) and PolyEditTool ( https://docs.bokeh.org/en/latest/docs/user_guide/tools.html#PolyEditTool ) but seems not to work. Any idea?

This is the sample code using bokeh and networrkx:

import networkx as nx

from bokeh.io import output_file, show ,curdoc
from bokeh.models import (BoxZoomTool, Circle, HoverTool,
                          MultiLine, Plot, Range1d, ResetTool,Dropdown,CustomJS)
from bokeh.palettes import Spectral4
from bokeh.plotting import from_networkx
from bokeh.layouts import column


# Prepare Data
G = nx.karate_club_graph()

SAME_CLUB_COLOR, DIFFERENT_CLUB_COLOR = "black", "red"
edge_attrs = {}

for start_node, end_node, _ in G.edges(data=True):
    edge_color = SAME_CLUB_COLOR if G.nodes[start_node]["club"] == G.nodes[end_node]["club"] else DIFFERENT_CLUB_COLOR
    edge_attrs[(start_node, end_node)] = edge_color

nx.set_edge_attributes(G, edge_attrs, "edge_color")


# Show with Bokeh
plot = Plot(plot_width=400, plot_height=400,
            x_range=Range1d(-1.1, 1.1), y_range=Range1d(-1.1, 1.1))
plot.title.text = "Graph Interaction Demonstration"



graph_renderer = from_networkx(G, nx.spring_layout, scale=1, center=(0, 0))

graph_renderer.node_renderer.glyph = Circle(size=15, fill_color=Spectral4[0])
graph_renderer.edge_renderer.glyph = MultiLine(line_color="edge_color", line_alpha=0.8, line_width=1)
plot.renderers.append(graph_renderer)

node_hover_tool = HoverTool(tooltips=[("index", "@index"), ("club", "@club")])
plot.add_tools(node_hover_tool,asd, BoxZoomTool(), ResetTool())

output_file("interactive_graphs.html")
show(plot)

I've tried to add the PointDrawTool to the bokeh tools:

plot.add_tools(node_hover_tool,asd, BoxZoomTool(), ResetTool(),PointDrawTool()) 

But it doesn't allow you to drag the nodes.

I also tried with PolyDrawTool:

poly_edit_tool = PolyEditTool(renderers=[graph_renderer.node_renderer])
plot.add_tools(node_hover_tool,poly_edit_tool, BoxZoomTool(), ResetTool())

But I get this error:

File "/usr/local/lib/python3.8/dist-packages/bokeh/models/tools.py", line 1510, in _check_compatible_vertex_renderer
    glyph = self.vertex_renderer.glyph
AttributeError: 'NoneType' object has no attribute 'glyph'

Seems like this is currently (Bokeh 2.1.1) not supported.

There's an issue marked as "Discussion" about this functionality: https://github.com/bokeh/bokeh/issues/9399

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM