Python NetworkX中节点的简单着色

Python NetworkX中节点的简单着色,python,networkx,Python,Networkx,我有以下图表: 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 =

我有以下图表:

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

我将如何如上所示为各个节点着色?

您需要将
颜色传递给
nx.draw
函数中的
节点颜色属性。这是密码

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

下面是一个链接,指向上的工作代码

参考资料: