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 = ['yellow' if node.starswith('V') else 'red' if node.startswith('R', else 'black')]
plt.show()
如上所示,我将如何为各个节点着色?
解决方案
您需要将colors
as 传递给函数中的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上工作代码的链接。
参考:
推荐阅读
- ruby-on-rails - 如何在 redmine 插件中调用 redirect_to
- javascript - 如何在 Angularfire Ionic 的单独页面中显示 Firebase 详细信息 [已回答]
- rust - 如何将计算 9 位位掩码中的个数的 C 函数转换为 Rust?
- python - 如何将具有多个分隔符的 df 列拆分为不同的列?
- android - recyclerview 内的 RecyclerView 只显示父 recyclerview 的最后一项
- assembly - 使用天然气进行进口的正确方法
- reactjs - XML5632:只允许一个根元素 - Microsoft 加载项
- typescript - Jest Babel TypeScript 类类型参数 Unexpected Token
- python - 为什么硒找不到标签和类
- java - 合并排序的奇怪运行时间