Reputation: 3815
I am trying to plot a simple network with networkx using colors, however the colors i give the nodes are not shown on the graph...
import networkx as nx
G = nx.Graph()
G.add_nodes_from([
(4, {"color": "red"}),
(5, {"color": "green"}),
])
nx.draw_networkx(G)
draws this graph:
Why are these nodes not the color I assigned them to?
I am trying to reproduce the example from https://networkx.org/documentation/stable/tutorial.html
Upvotes: 0
Views: 413
Reputation: 153460
Try:
import networkx as nx
G = nx.Graph()
G.add_nodes_from([
(4, {"color": "red"}),
(5, {"color": "green"}),
])
nx.draw_networkx(G, node_color=[i['color'] for i in dict(G.nodes(data=True)).values()])
Output:
Upvotes: 1
Reputation: 142651
Example in documentation is misleading - and it doesn't even show image with colors.
Value {"color": "red"}
is not used to change color but only keep extra information in node. You could use {"first name": "James", "last name": "Bond", "number": "007"}
with the same result
To set color you have to use list when you draw them
nx.draw(G, node_color=['red', 'green', 'blue'], with_labels=True)
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_nodes_from([
(4, {"color": "red"}),
(5, {"color": "green"}),
(7, {"first name": "James", "last name": "Bond", "number": "007"}),
])
nx.draw(G, node_color=['red', 'green', 'blue'], with_labels=True)
plt.show()
Or you will have to use for
-loop to create list using data from nodes
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_nodes_from([
1,
2,
(4, {"color": "red"}),
(5, {"color": "green"}),
(7, {"first name": "James", "last name": "Bond", "number": "007"}),
8,
9,
('Hello', {"color": "red"}),
])
#color_map = ['red', 'green', 'blue']
color_map = []
for node in G:
print(G.nodes[node])
if 'color' in G.nodes[node]:
color_map.append( G.nodes[node]['color'] )
else:
color_map.append('blue')
nx.draw(G, node_color=color_map, with_labels=True)
plt.show()
Upvotes: 1