Color nodes by Networkx node attribute with Bokeh

2020-07-24 03:29发布

问题:

I'm trying to use bokeh to create an interactive network visualization. I understand how to add attribtue data to the bokeh graph, but I'm not sure how to assign a fill color based on the node attribute.

I've been following all of the bokeh examples that I can find, but I can't seem to figure it out.

How can I adjust my code below to color the nodes by their NetworkX node attributes?

import networkx as nx
from bokeh.io import show, output_notebook
from bokeh.plotting import figure
from bokeh.models import Circle, HoverTool, TapTool, BoxSelectTool
from bokeh.models.graphs import from_networkx

output_notebook()

# create a sample graph
G = nx.karate_club_graph()

# create the plot
plot = figure(x_range=(-1.1, 1.1), y_range=(-1.1, 1.1))

# add tools to the plot
plot.add_tools(HoverTool(tooltips=[("Name", "@name"), 
                                   ("Club", "@club")]), 
               TapTool(), 
               BoxSelectTool())

# create bokeh graph
graph = from_networkx(G, nx.spring_layout, iterations=1000, scale=1, center=(0,0))

# add name to node data
graph.node_renderer.data_source.data['name'] = list(G.nodes())

# add club to node data
graph.node_renderer.data_source.data['club'] = [i[1]['club'] for i in G.nodes(data=True)]

# set node size
graph.node_renderer.glyph = Circle(size=10)

plot.renderers.append(graph)
show(plot)

回答1:

The question is a little vague, so I am not sure the code below is exactly what you are asking for. (Is the "node" attribute what you copy in to the "names" column? I think so...) But regardless, you can use linear_cmap to colormap the fill_color according to any CDS column:

from bokeh.transform import linear_cmap
graph.node_renderer.glyph = Circle(
    size=10, 
    fill_color=linear_cmap('name', 'Spectral8', min(G.nodes()), max(G.nodes()))
)

Alternatively if the column is string factors, you could also use factor_cmap.