fbrundu fbrundu - 1 year ago 124
Python Question

How to deal with overlapping nodes in networkx graphics

I am trying to make a graphics in networkx in which groups of nodes are linked as in this figure:


However, some nodes shows up, the others are rendered with a neutral color.

I want to know if there is a way to either:

  • color only one node for each subgroup (e.g. one node with red color) - the others with the neutral color;

  • or color all nodes.

This is my code:

def draw_graph(transactions, method, suffix):

G = nx.Graph()

# get the string prefixes for each group (column of nodes)
# possible prefixes are: aa, bb, cc, etc.
prefixes = [c[:2] for c in classifiers]

# for each transaction, use also a unique index (i_t)
for i_t, t in enumerate(transactions):

# tid is the groups signature, e.g. if the tuple of
# classification is ('1', '2', '1') tid is 121
# tid has always 3 characters - there are only 3
# with at maximum 7 classifications in each group
tid = ''.join([c[2] for c in t])

# nodes have name the concatenated string composed of:
# * classification (e.g. aa1) <- please note prefix
# * tid (e.g. 121)
# * unique identifier
node1 = t[0] + tid + str(i_t)
node2 = t[1] + tid + str(i_t)
node3 = t[2] + tid + str(i_t)

# link correspondent nodes on each group
G.add_edge(node1, node2, weight=0.2)
G.add_edge(node2, node3, weight=0.2)

# based on prefix decide in which group store the node
pos = {}
group1 = []
group2 = []
group3 = []
for node in G.nodes():
if node.startswith(prefixes[0]):
elif node.startswith(prefixes[1]):

# sort each group by classification AND tid
group1.sort(key=lambda x: x[2:6])
group2.sort(key=lambda x: x[2:6])
group3.sort(key=lambda x: x[2:6])

# define position for each node based on group and index
# of node inside the group
for i_group, group in enumerate([group1, group2, group3]):
for i_node, node in enumerate(group):
xpos = float(i_group) * 2
ypos = float(i_node) / len(group)
pos[node] = [xpos, ypos]

# decide node color based on classification (nn[2]).
# avail_colors is a list of colors defined outside this method
node_color = [avail_colors[int(nn[2])] for nn in G.nodes()]

# draw each node with correspondent position and color
nx.draw_networkx_nodes(G, pos, node_size=200, node_color=node_color)

# draw edges with defined weight (not used in this example)
for (u, v, d) in G.edges(data=True):
w = d['weight']
nx.draw_networkx_edges(G, pos, edgelist=[(u, v)], width=w)


Hope it is understandable. If not ask me info.


Answer Source

I found that, in my case, the thing that solves my problem is setting


in draw_networkx_nodes(), because it was the border of the circles that created the effect of overlapping.

Hope it helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download