如何使用Networkx绘制子图 [英] How to draw subgraph using networkx

查看:1330
本文介绍了如何使用Networkx绘制子图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试根据节点名称列表从networkx的karate_club_graph绘制子图,但失败了.我想展示如何绘制子图?

I try to draw subgraph from karate_club_graph in networkx based on a list of nodes'name but failed. How could draw subgraph as I want to show?

import networkx as nx
from matplotlib import pylab as pl

G = nx.karate_club_graph()
res = [0,1,2,3,4,5]
new_nodes = []
for n in G.nodes(data=True):
  if n[0] in res:
    new_nodes.append(n)

k = G.subgraph(new_nodes)
pos = nx.spring_layout(k)

pl.figure()
nx.draw(k, pos=pos)
pl.show()

推荐答案

您遇到的问题是您的subgraph命令告诉它创建一个带有节点列表的子图,其中每个元素不仅是节点名称,而且还包括节点名称有关该节点名称的数据.命令G.subgraph仅需要节点名称列表.

The problem you're having is that your subgraph command is telling it to make a subgraph with a nodelist where each element is not just the node name, but also the data about that node name. The command G.subgraph needs just the list of node names.

解决此问题的最简单方法就是

The easiest way to fix this is just

k = G.subgraph(res)

即使res中的某些节点不在G中,它也将起作用.

which will work even if some of the nodes in res aren't in G.

我将进行此更改,还将展示如何通过在绘图中添加其他子图来多次绘制具有一致位置的图形.它将绘制您的k,然后是由不在k中的所有节点组成的子图.请注意,由于subgraph的工作原理,两者之间将不存在任何边缘.

I'll do this change and also show how to draw several times with consistent positions by adding an additional subgraph to plot. It will plot your k and then the subgraph made up of all nodes not in k. Note that no edges will exist between the two because of how subgraph works.

import networkx as nx
from matplotlib import pylab as pl

G = nx.karate_club_graph()
res = [0,1,2,3,4,5, 'parrot'] #I've added 'parrot', a node that's not in G
                              #just to demonstrate that G.subgraph is okay
                              #with nodes not in G.    
pos = nx.spring_layout(G)  #setting the positions with respect to G, not k.
k = G.subgraph(res)  

pl.figure()
nx.draw_networkx(k, pos=pos)

othersubgraph = G.subgraph(range(6,G.order()))
nx.draw_networkx(othersubgraph, pos=pos, node_color = 'b')
pl.show()

G.nodes()调用中包含data=True的效果如下:

The effect of having data=True in the G.nodes() call is as follows:

print G.nodes()
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]
print G.nodes(data=True)
> [(0, {'club': 'Mr. Hi'}), (1, {'club': 'Mr. Hi'}), (2, {'club': 'Mr. Hi'}), (3, {'club': 'Mr. Hi'}), (4, {'club': 'Mr. Hi'}), (5, {'club': 'Mr. Hi'}), (6, {'club': 'Mr. Hi'}), (7, {'club': 'Mr. Hi'}) ...  *I've snipped stuff out*

所以G.nodes()仅给出了节点名称. G.nodes(data=True)给出一个元组列表,其中元组名称为第一个条目,而字典则显示第二个条目中有关这些节点的任何数据.

So G.nodes() just gives the node names. G.nodes(data=True) gives a list of tuples, which have node name as the first entry and a dict showing any data about those nodes in the second entry.

这篇关于如何使用Networkx绘制子图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆