根据节点的属性NetworkX将图划分为太阳图 [英] partition graph into sungraphs based on node's attribute NetworkX
问题描述
我正在使用Networkx计算图形的一些度量,例如直径,聚类系数等.直接对整个图形执行此操作很简单.我感兴趣的是在具有相同属性(例如颜色)的节点之间找到这些度量.我在考虑是否可以将图划分为不同的子图,其中每个子图中的节点具有相同的颜色,那么我可以继续进行并测量该子图中的直径.所以我的问题是:是否可以将一个图划分为包含相同颜色节点的子图?
I'm using Networkx to compute some measures of a graph such as diameter, clustering coefficient, etc. It's straight forward how to do this for graph as a whole. What I'm interested in is finding these measures between nodes that have same attribute(say color). I'm thinking if I could partition the graph into different sub graphs, where nodes in each sub graph are of the same color, then I could accomplish go ahead and measure diameter in this sub graph. So my question is: Is there a way to partition a graph into sub graphs which contain nodes of same color?
我真的很感谢任何见解.
I would really appreciate any insight.
推荐答案
使用演示
import networkx as nx
G = nx.Graph()
G.add_nodes_from([1, 2, 3], color="red")
G.add_nodes_from([4, 5, 6])
G.nodes # NodeView((1, 2, 3, 4, 5, 6))
# create generator
nodes = (
node
for node, data
in G.nodes(data=True)
if data.get("color") == "red"
)
subgraph = G.subgraph(nodes)
subgraph.nodes # NodeView((1, 2, 3))
旧版NetworkX的
遍历( Graph.subgraph()
,它将返回这些节点及其内部边缘的副本.
older NetworkX's
Iterate over (Graph.iter_nodes()
) and filter the nodes based on your criteria. Pass that list to Graph.subgraph()
and it'll return a copy of those nodes and their internal edges.
例如:
G = nx.Graph()
# ... build or do whatever to the graph
nodes = (n for n, d in G.nodes_iter(data=True)) if d.get('color') == 'red')
subgraph = G.subgraph(nodes)
这篇关于根据节点的属性NetworkX将图划分为太阳图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!