Skip to content

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

@floklimm

Description

@floklimm

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.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions