3

整数パーティションのコードを作成し、各ノードがパーティションであるグラフを作成しています。グラフ内のノードに {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)

しかし、私が望むのは、すでに構築されたグラフの個々のノードにラベルを付けることです!

ここでコードを提供しているので、理解を深めることができます。

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()

私を助けてください。

どうもありがとうございました

4

1 に答える 1

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))

収量

ここに画像の説明を入力

于 2013-07-18T10:05:43.303 に答える