【问题标题】:Draw node shape and node color by attribute using networkx使用networkx按属性绘制节点形状和节点颜色
【发布时间】:2018-03-22 12:21:37
【问题描述】:

在图表G 中,我有一组节点。其中一些具有属性Type,可以是MASTERDOC。其他人没有 a 类型定义:

>>> import networkx as nx
>>> import matplotlib.pyplot as plt
>>> G=nx.Graph()
[...]
>>> G.node['ART1']
{'Type': 'MASTER'}
>>> G.node['ZG1']
{'Type': 'DOC'}
>>> G.node['MG1']
{}

然后我使用

绘制图表
>>> nx.draw(G,with_labels = True)
>>> plt.show()

现在我得到一个带有红色圆圈的图表。我怎样才能得到例如 ART 的蓝色循环 DOC 的红色方块 所有未定义的紫色循环 在我的情节中?

【问题讨论】:

  • nx.draw() 有一个可选关键字node_color,你应该试试。

标签: python matplotlib networkx


【解决方案1】:

有多种方法可以根据属性选择节点。这是使用get_node_attributes 和列表理解来获取子集的方法。然后绘图函数接受 nodelist 参数。

应该很容易扩展到更广泛的条件集或根据这种方法修改每个子集的外观以满足您的需求

import networkx as nx

# define a graph, some nodes with a "Type" attribute, some without.
G = nx.Graph()
G.add_nodes_from([1,2,3], Type='MASTER')
G.add_nodes_from([4,5], Type='DOC')
G.add_nodes_from([6])


# extract nodes with specific setting of the attribute
master_nodes = [n for (n,ty) in \
    nx.get_node_attributes(G,'Type').iteritems() if ty == 'MASTER']
doc_nodes = [n for (n,ty) in \
    nx.get_node_attributes(G,'Type').iteritems() if ty == 'DOC']
# and find all the remaining nodes.
other_nodes = list(set(G.nodes()) - set(master_nodes) - set(doc_nodes))

# now draw them in subsets  using the `nodelist` arg
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, nodelist=master_nodes, \
    node_color='red', node_shape='o')
nx.draw_networkx_nodes(G, pos, nodelist=doc_nodes, \
    node_color='blue', node_shape='o')
nx.draw_networkx_nodes(G, pos, nodelist=other_nodes, \
    node_color='purple', node_shape='s')

【讨论】:

  • 我忘了提到我在 python3.6 中工作:适用于每个遇到此解决方案问题的人。使用items() 而不是iteritems() - nx.get_node_attributes(G,'Type').items()
  • 我怎样才能用这个传递标签?
猜你喜欢
  • 2011-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-11
  • 2021-04-30
  • 2019-03-29
  • 2012-03-27
相关资源
最近更新 更多