Python 如何在networkx中将标签添加到图形中的节点?
我正在为整数分区编写代码,并构造一个图,其中每个节点都是一个分区。我想用{2,1,1}、{1,1,1}、{2,2}等分区元素来标记图中的节点 所以我想知道,如何在networkx中标记节点 我已经看到了标记节点的代码,但我没有得到它。 代码如下:Python 如何在networkx中将标签添加到图形中的节点?,python,integer,partitioning,networkx,Python,Integer,Partitioning,Networkx,我正在为整数分区编写代码,并构造一个图,其中每个节点都是一个分区。我想用{2,1,1}、{1,1,1}、{2,2}等分区元素来标记图中的节点 所以我想知道,如何在networkx中标记节点 我已经看到了标记节点的代码,但我没有得到它。 代码如下: nx.draw_networkx_nodes(G,pos, nodelist=[0,1,2,3], node_color='r',
nx.draw_networkx_nodes(G,pos,
nodelist=[0,1,2,3],
node_color='r',
node_size=500,
alpha=0.8)
但我想要的是标记已经构建的图的各个节点
我在这里提供我的代码,以便您更好地理解它
import networkx as nx
from matplotlib import pylab as pl
def partitions(num):
final=[[num]]
for i in range(1,num):
a=num-i
res=partitions(i)
for ele in res:
if ele[0]<=a:
final.append([a]+ele)
return final
def drawgraph(parlist):
#This is to draw the graph
G=nx.Graph()
length=len(parlist)
print "length is %s\n" % length
node_list=[]
for i in range(1,length+1):
node_list.append(i)
G.add_cycle(node_list)
nx.draw_circular(G)
pl.show()
将networkx导入为nx
从matplotlib导入pylab作为pl
def分区(num):
最终=[[num]]
对于范围内的i(1,num):
a=num-i
res=分区(i)
对于res中的ele:
如果ele[0]因为您的节点列表
是由整数组成的,那么您的节点将这些整数的字符串表示形式作为标签。但是节点可以是任何可散列对象,而不仅仅是整数。因此,最简单的方法是使您的节点列表
成为parlist
中项目的字符串表示形式。(parlist
中的项目是列表,它们是可变的,因此不可散列。这就是为什么我们不能将parlist
用作我们的节点列表
)
还有一个函数,我们可以使用它,但是我认为首先给节点一个正确的标签更简单
import networkx as nx
import matplotlib.pyplot as plt
def partitions(num):
final = [[num]]
for i in range(1, num):
a = num - i
res = partitions(i)
for ele in res:
if ele[0] <= a:
final.append([a] + ele)
return final
def drawgraph(parlist):
G = nx.Graph()
length = len(parlist)
print "length is %s\n" % length
node_list = [str(item) for item in parlist]
G.add_cycle(node_list)
pos = nx.circular_layout(G)
draw_lifted(G, pos)
def draw_lifted(G, pos=None, offset=0.07, fontsize=16):
"""Draw with lifted labels
http://networkx.lanl.gov/examples/advanced/heavy_metal_umlaut.html
"""
pos = nx.spring_layout(G) if pos is None else pos
nx.draw(G, pos, font_size=fontsize, with_labels=False)
for p in pos: # raise text positions
pos[p][1] += offset
nx.draw_networkx_labels(G, pos)
plt.show()
drawgraph(partitions(4))
将networkx导入为nx
将matplotlib.pyplot作为plt导入
def分区(num):
最终=[[num]]
对于范围内的i(1,num):
a=num-i
res=分区(i)
对于res中的ele:
如果ele[0]感谢您的回复。我得到了答案,现在,我必须理解你的代码。但是在这里,每个节点应该只有两条边,但是在代码中,每个节点都有不止一条和两条边。我们能克服吗?因为它看起来像一个非常复杂的网络。如果不可能,没问题。再次非常感谢!你能告诉我关于这个主题的更多信息(如文档、示例等)在哪里更容易理解,这样我就可以去那里搜索,而不是麻烦你吗?我所知道的最好的资源是和,例如。我们能在这方面实现测试驱动开发吗?如果是,我们怎么做?你能举几个例子吗。我试图理解TDD,但我在网上找不到太多信息,或者我没有找到合适的必要信息。我只知道一点基本知识。请帮我做这件事。非常感谢。