still_learning
still_learning

Reputation: 806

Wrong colors assigned to nodes in networkx

I am having difficulties in plotting the right colour in a network. This is my dataset, where users are nodes and values is the user who they are linked to.

    User        Val     Color   
92  Laura   NaN      red
100 Laura   John    red
148 Laura   Mike    red
168 Laura   Mirk    red
293 Laura   Sara     red
313 Laura   Sim  red
440 Martyn  Pierre   orange
440 Martyn  Hugh    orange
440 Martyn  Lauren  orange
440 Martyn  Sim     orange

I am using the following code:

G = nx.from_pandas_edgelist(df, 'User', 'Val')
labels = [i for i in dict(G.nodes).keys()]
labels = {i:i for i in dict(G.nodes).keys()}
colors = df[["User", "Color"]].drop_duplicates()["Color"]

plt.figure(3,figsize=(30,50)) 
pos = nx.spring_layout(G) 
nx.draw(G, node_color = colors, pos = pos)
net = nx.draw_networkx_labels(G, pos = pos)

where I tried to assign the colors in Color column to the user. My expected output would be:

Laura (node) in red, Martyn (node) in orange and others (John, Mike, Mirk, ...) in green.

Upvotes: 0

Views: 323

Answers (1)

mathfux
mathfux

Reputation: 5949

Colors itself are not wrong. You're just trying to assign a color to each couple of nodes which is most likely to be coloring of edges. In that case you need to replace node_color keyword with edge_color.

G = nx.from_pandas_edgelist(df, 'User', 'Val')
colors = df[["User", "Color"]].drop_duplicates()["Color"]

plt.figure(figsize=(3, 3))
pos = nx.spring_layout(G)
nx.draw(G, edge_color = colors, pos = pos)
net = nx.draw_networkx_labels(G, pos = pos)
plt.show()

This is df I'm working with:

t = '''
User        Val     Color   
92  Laura   NaN      red
100 Laura   John    red
148 Laura   Mike    red
168 Laura   Mirk    red
293 Laura   Sara     red
313 Laura   Sim  red
440 Martyn  Pierre   orange
440 Martyn  Hugh    orange
440 Martyn  Lauren  orange
440 Martyn  Sim     orange'''
from io import StringIO
df = pd.read_csv(StringIO(t), sep='\s+')

Output

enter image description here

Upvotes: 2

Related Questions