rtzu
rtzu

Reputation: 49

Networkx: nodes in the network disappear when colouring

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:

  1. The code colours the node, but at the same time makes a lot of the other nodes disappear. What am I doing wrong?
  2. Once 1) is resolved, what is the best way to modify the code to colour several nodes?

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

Answers (1)

thorntonc
thorntonc

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()

networkx graph

Upvotes: 1

Related Questions