简体   繁体   中英

Simple coloring of nodes in NetworkX

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?

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM