Reputation: 49
I have a network graph in networkx created from a dictionary and want to colour a subset of nodes in a specific colour.
I created the original network graph using
nx.draw_networkx(g, with_labels=False, node_size=20)
Then I tried to colour a specific node in a different colour using the suggested solution in How to set colors for nodes in NetworkX?
Problems:
Thank you for your help!
for node in g:
if node == 'Bob':
color_map.append('red')
else:
color_map.append('blue')
nx.draw(g, node_color=color_map, with_labels=False, node_size=20)
Upvotes: 1
Views: 206
Reputation: 2126
Here is a code example where you can color code multiple nodes with a mapping dictionary. I was not able to reproduce the issue of missing nodes, run this code with your data and see if any nodes are missing.
import networkx as nx
from matplotlib import pyplot as plt
g = nx.Graph()
g.add_edges_from([('Bob', 'Steve'), ('Bob', 'Jeff'), ('Jeff', 'George'), ('Jeff', 'Steve')])
node_map = {'Bob': 'red', 'Jeff': 'green'}
color_map = [node_map.get(n, 'blue') for n in g.nodes]
nx.draw_networkx(g, node_color=color_map, with_labels=True, node_size=200)
plt.show()
Upvotes: 1