代码之家  ›  专栏  ›  技术社区  ›  Soerendip

如何在用holoviews/bokeh绘制的networkx图形中更改颜色?

  •  0
  • Soerendip  · 技术社区  · 6 年前

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

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

    enter image description here

    2 回复  |  直到 6 年前
        1
  •  0
  •   philippjfr    6 年前

    当前定义的图形没有定义任何属性,但仍可以按节点索引着色。要按特定节点属性着色,可以使用 color_index 选项以及 cmap . 下面是我们如何通过“索引”着色

    graph = hv.Graph.from_networkx(G, nx.layout.spring_layout)
    graph.options(color_index='index', cmap='Category10').redim.range(**padding)
    

    如果要在下一版本之前手动添加节点属性,则可以传入一个数据集,其中包含一个定义节点索引的键维度和任何要添加的属性,这些属性定义为值维度,例如:

    nodes = hv.Dataset([(1, 'A'), (2, 'B'), (3, 'A'), (4, 'B')], 'index', 'some_attribute')
    hv.Graph.from_networkx(G, nx.layout.spring_layout, nodes=nodes).options(color_index='some_attribute', cmap='Category10')
    
        2
  •  0
  •   Soerendip    6 年前

    %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')
    

    enter image description here