首页 > 解决方案 > 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 = ['yellow' if node.starswith('V') else 'red' if node.startswith('R', else 'black')]
plt.show()

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

标签: pythonnetworkx

解决方案


您需要将colorsas 传递给函数中的node_color属性。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()

节点颜色

这是Google Colab Notebook上工作代码的链接。

参考:


推荐阅读