首页 > 解决方案 > 如何更改使用 holoviews/bokeh 绘制的 networkx 图中的颜色?

问题描述

如何更改以下示例中各个节点的颜色?

%pylab inline

import pandas as pd
import networkx as nx
import holoviews as hv

hv.extension('bokeh')
G = nx.Graph()
ndxs = [1,2,3,4]
G.add_nodes_from(ndxs)
G.add_weighted_edges_from([(1,2,0), (1,3,1), (1,4,-1),
                           (2,4,1), (2,3,-1), (3,4,10)]) 

hv.extension('bokeh')
%opts Graph [width=400 height=400]
padding = dict(x=(-1.1, 1.1), y=(-1.1, 1.1))
hv.Graph.from_networkx(G, nx.layout.spring_layout).redim.range(**padding)

在此处输入图像描述

标签: networkxbokehholoviews

解决方案


感谢 Philippjfr,这是一个很好的解决方案(使用当前开发版本的 holoviews),它使用节点属性进行着色:

%pylab inline

import pandas as pd
import networkx as nx
import holoviews as hv

hv.extension('bokeh')
G = nx.Graph()
ndxs = [1,2,3,4]
G.add_nodes_from(ndxs)
G.add_weighted_edges_from([(1,2,0), (1,3,1), (1,4,-1),
                           (2,4,1), (2,3,-1), (3,4,10)]) 

attributes = {ndx: ndx%2 for ndx in ndxs}
nx.set_node_attributes(G, attributes, 'some_attribute')

%opts Graph [width=400 height=400]
padding = dict(x=(-1.1, 1.1), y=(-1.1, 1.1))
hv.Graph.from_networkx(G, nx.layout.spring_layout)\
    .redim.range(**padding)\
    .options(color_index='some_attribute', cmap='Category10')

在此处输入图像描述


推荐阅读