Jaqueline Passos
Jaqueline Passos

Reputation: 1389

How can I map the colors of a node according to the value of a attribute using networkx?

I have a network and a attribute sentiment for each node of this network. This attribute is a float wich varies from -1 to 1, approximatedly. I want to collor the nodes of the network according to this attribute, meaning that when the value is closer to 1 the color is stronger(alpha 1) or blue and when the attribute is closer to -1, the color is weak (alpha closer to 0) or red. How can I do that?

Here is a part of my code:

#sentiment
G.node[tweet['user'][ u'id']]['sentiment'] = 0.92762

#plot
color_map = {0:'#3B5998', 1:'#E4AF48'} 
nx.draw_networkx(G, node_color=[color_map[G.node[node]['match']] for node in G], with_labels=False)

it returns the following error:

Traceback (most recent call last):
File "graph_better.py", line 38, in <module>
nx.draw_networkx(G, node_color=[color_map[G.node[node]['sentiment']] for node in G], with_labels=False)
KeyError: -0.351317

Upvotes: 0

Views: 920

Answers (1)

Mikk
Mikk

Reputation: 814

Your color_map is a dictionary with only two keys: 0 and 1. Any value in between is not a correct key for the dictionary, thus you get a KeyError.

To fix your code you have to: first pass to the node_color argument the list of values. In your case it will be:

node_color = [G.node[node]['sentiment'] for node in G]

Second, you need to use the cmap argument, for example:

cmap = plt.cm.Reds_r

So in the end you'll have:

nx.draw_networkx(G, node_color = [G.node[node]['sentiment'] for node in G], cmap = plt.cm.Reds_r, with_labels = False)

Now the only thing left to you is to pass you proper color map to cmap.

Upvotes: 1

Related Questions