Color nodes by Networkx node attribute with Bokeh

大城市里の小女人 提交于 2020-01-01 18:28:28

问题


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.



来源:https://stackoverflow.com/questions/50420584/color-nodes-by-networkx-node-attribute-with-bokeh

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