簡體   English   中英

如何在networkx的圖形中的節點上添加標簽?

[英]How to add labels to nodes in a graph in 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)

但是我想要標記已經構造的圖形的各個節點!

我在這里提供我的代碼,以便您可以更好地理解它。

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

請幫我。

非常感謝你

由於您的node_list由整數組成,因此您的節點將這些整數的字符串表示形式作為標簽。 但是您的節點可以是任何可哈希對象,而不僅僅是整數。 因此,最簡單的方法是使node_list成為parlist各項的字符串表示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))

產量

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM