我正在尝试使用 Bokeh 来创建交互式网络可视化。我了解如何将属性数据添加到 Bokeh 图,但我不确定如何根据节点属性分配填充颜色。
我一直在关注所有 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)
请您参考如下方法:
这个问题有点含糊,所以我不确定下面的代码是否正是您所要求的。 (“节点”属性是您复制到“名称”列中的内容吗?我认为是...)但是无论如何,您可以使用 linear_cmap根据任何 CDS 列对 fill_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。
