0

How can I change the color of individual nodes in the following example?

%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

Soerendip
  • 7,684
  • 15
  • 61
  • 128

2 Answers2

0

The graph as you currently define it does not define any attributes but you could still color by the node index. To color by a particular node attribute you can use the color_index option along with a cmap. Here's how we would color by the 'index'

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

If you do have attributes defined on the nodes the next version of HoloViews (1.10.5) due to be released this week will be able to extract them automatically and let you use the same approach to color by those variables.

If you want to manually add node attributes until the next release you can pass in a Dataset with a single key dimension defining the node indices and any attributes you want to add defined as value dimensions, e.g.:

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')
philippjfr
  • 3,997
  • 14
  • 15
  • How can you add an attribute and then color the nodes by it though? – Soerendip May 24 '18 at 12:33
  • I've added an example of manually adding node attributes, as I point out in future you can just define the node attributes on the networkx graph. – philippjfr May 24 '18 at 12:54
  • Would you be able to share an example for the latter one? I have the development version installed, I think, the feature is already implemented. Thanks!! – Soerendip May 24 '18 at 12:56
0

Thanks to Philippjfr, here is a nice solution (using the current development version of holoviews) that uses node attributes for coloring:

%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

Soerendip
  • 7,684
  • 15
  • 61
  • 128