Networkx节点属性的颜色节点与Bokeh

时间:2018-05-19 00:06:47

标签: python networkx bokeh

我尝试使用散景来创建交互式网络可视化。我理解如何将attribtue数据添加到散景图中,但我不确定如何根据节点属性分配填充颜色。

我一直在关注我能找到的所有bokeh examples,但我似乎无法弄明白。

如何调整下面的代码,按照NetworkX节点属性为节点着色?

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)

Bokeh Graph

1 个答案:

答案 0 :(得分:0)

问题有点模糊,所以我不确定下面的代码是否正是您所要求的。 (“node”属性是您复制到“names”列的内容吗?我是这么认为的......)但无论如何,您可以根据任何CDS列使用linear_cmapfill_color进行颜色映射:

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()))
)

或者,如果列是字符串因子,您也可以使用factor_cmap

enter image description here