Reputation: 4767
I have the following graph:
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_edge('V1', 'R1')
G.add_edge('R1', 'R2')
G.add_edge('R2', 'R3')
G.add_edge('R2', 'R4')
G.add_edge('R3', 'Z')
G.add_edge('R4', 'Z')
nx.draw(G, with_labels=True)
colors = ['yellow' if node.starswith('V') else 'red' if node.startswith('R', else 'black')]
plt.show()
How would I colorize the various nodes as show above?
Upvotes: 0
Views: 257
Reputation: 8801
You need to pass the colors
as to the node_color
attribute in the nx.draw
function. Here is the code,
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_edge('V1', 'R1')
G.add_edge('R1', 'R2')
G.add_edge('R2', 'R3')
G.add_edge('R2', 'R4')
G.add_edge('R3', 'Z')
G.add_edge('R4', 'Z')
# I have added a function which returns
# a color based on the node name
def get_color(node):
if node.startswith('V'):
return 'yellow'
elif node.startswith('R'):
return 'red'
else:
return 'black'
colors = [ get_color(node) for node in G.nodes()]
# ['yellow', 'red', 'red', 'red', 'red', 'black']
# Now simply pass this `colors` list to `node_color` attribute
nx.draw(G, with_labels=True, node_color=colors)
plt.show()
Here is a link to working code on Google Colab Notebook.
References:
Upvotes: 1