如何在networkx中的图形中为节点添加标签?

Raj*_*ndu 1 python integer partitioning networkx

我正在为整数分区编写代码并构建一个图,其中每个节点都是一个分区.我想用图像中的节点标记{2,1,1},{1,1,1,1},{2,2}等分区元素.

所以我想知道如何在networkx中标记节点.

我已经看到了标记节点的代码,但我没有得到它.代码如下:

nx.draw_networkx_nodes(G,pos,
                       nodelist=[0,1,2,3],
                       node_color='r',
                       node_size=500,
                    alpha=0.8)
Run Code Online (Sandbox Code Playgroud)

但我想要的是标记已经构建的图形的各个节点!

我在这里提供我的代码,以便您可以更好地理解它.

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()
Run Code Online (Sandbox Code Playgroud)

请帮我.

非常感谢你

unu*_*tbu 7

由于您node_list是由整数组成的,因此您的节点将这些整数的字符串表示形式作为标签.但是您的节点可以是任何可哈希的对象,而不仅仅是整数.因此,最简单的方法是使您node_list的项目的字符串表示形式parlist.(parlist列表中的项目是可变的,因此不可清除.这就是为什么我们不能只parlist用作我们的node_list.)

还有函数nx.relabel_nodes,我们可以使用它,但我认为只是首先给节点提供正确的标签更简单.

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))
Run Code Online (Sandbox Code Playgroud)

产量

在此输入图像描述