benmaier / netwulf

Interactive visualization of networks based on Ulf Aslak's d3 web app.
MIT License
294 stars 26 forks source link

Colouring nodes by property (e.g., degree) #38

Open floklimm opened 4 years ago

floklimm commented 4 years ago

This is not really a bug but rather a workaround that I wanted to make available for others (and maybe you want to integrate it at some point into the library itself).

I wanted to color all nodes by a node property. It is possible to achieve this by using the coloring by `group'. One only has to assign each node an html color according to its value.

Below I give a minimal example that colors a Barabasi-Albert network by node degree.

The result is this image (where nodes are also sized proportionally to their degree). I choose the RGB color to be (X,0,20), such that it is from dark blue to red but this can be adapted as needed. Probably one could also automatically use an existing colormap.

image

G = nx.barabasi_albert_graph(100,1) # construct a BA graph
deg = [val for (node, val) in G.degree()] # compute its degree
# prepare
degreeColor =[]
valueToPlot = np.log10(deg)
# we rescale the colours to be in the RGB format (0 to 255 for three colours)
valueToPlotRescaled = 255*(valueToPlot - np.min(valueToPlot))/np.max(valueToPlot)

for i in valueToPlotRescaled:
    color = '#%02x%02x%02x' % (int(i), 0, 50) # here we use (X,0,50) as RGB with X beign the log(degree) for eahc node
    degreeColor.append(color)
# zip it up into a dictionary and set it as node attribute
dictionaryColor = dict(zip(list(G.nodes), degreeColor))
nx.set_node_attributes(G, dictionaryColor,"group")
# The actual illustration
network, config = wulf.visualize(G, plot_in_cell_below=False)
fig, ax = wulf.draw_netwulf(network)
plt.savefig("BAnetworkWithDegreeColoured.pdf")

Let me know if there is an easier way to achieve this; anyways, I thought that could be useful for other users.

benmaier commented 4 years ago

thank you for this example! I'm doing this in a similar way when needed. Only I'm using the property color instead of group. e.g.

FBC = FB.copy()
for n in FB.nodes(data=False):
    _col = '#%02x%02x%02x' % tuple(list([int(255*_) for _ in degree_scale[n][:3]]))
    FBC.node[n]['color'] = _col

I guess we should mention that in the docs, doesn't seem to be in there.

floklimm commented 4 years ago

Thanks, that is even easier!

Yes, it would be great if there would be a full list of all properties that can be given to Netwulf in the documentation.