I'm creating a graph with Networkx on python 3.8 and I want to assign a color to every single node by the time i'm appending the node to the graph, as follow:
if raw_output in occurrencies_dict_gold:
G.add_node(raw_output, color = 'g')
else:
G.add_node(raw_output, color = 'r')
print('RED STATE : ', raw_output)
in which i check that a node doesn't exist in a particular dictionary previously created, and i consequently add the node with its color.
I do the same for edges
if transition_key in transitions_dict_gold:
G.add_edge(previous_raw_output, raw_output, color = 'g')
else:
G.add_edge(previous_raw_output, raw_output, color = 'r')
At printing stage i do the following:
edges = G.edges()
nodes = G.nodes()
e_colors = [G[u][v]['color'] for u,v in edges]
n_colors = [G[u]['color'] for u in nodes]
nx.draw(G, node_color=n_colors, edge_color=e_colors, with_labels=True)
plt.show()
plt.savefig("filename.png")
which works perfectly if i only do it for the edges, while if i try as written above i recieve the following message:
Traceback (most recent call last):
File "result_iterative_parser.py", line 157, in <module>
n_colors = [G[u]['color'] for u in nodes]
File "result_iterative_parser.py", line 157, in <listcomp>
n_colors = [G[u]['color'] for u in nodes]
File "/anaconda3/lib/python3.8/site-packages/networkx/classes/coreviews.py", line 51, in __getitem__
return self._atlas[key]
KeyError: 'color'
any idea?