簡體   English   中英

如何在python networkx中顯示圖形節點的標簽

[英]How can I display label for graph nodes in python networkx

我有以下代碼來可視化 networkx 圖:

node_positions = networkx.spring_layout(graph)
networkx.draw_networkx_nodes(graph, node_positions)
networkx.draw_networkx_edges(graph, node_positions, style='dashed')

我想在每個節點上顯示節點標簽。 graph.nodes()會給我所有節點的列表,但我如何使用它們來標記圖形上的節點?

我試過這個,但它不起作用:

networkx.draw_networkx_labels(graph,node_positions,graph.nodes(data="false"),font_size=16)

編輯:

我嘗試了以下並且它現在可以工作:

for node,_ in graph.nodes(data="False"):
        labels[node] = node;
networkx.draw_networkx_labels(graph,node_positions,labels,font_size=16)

如果還有一些優雅的方法可以做到這一點,請告訴我。 我覺得創建新的 dict 是矯枉過正,多余的,不應該是必需的。

在此處輸入圖片說明 檢查nx.draw 源代碼繪圖文檔 我不太確定我是否正確回答了您的問題,因為根據我的理解,這是一個相當直接的問題,您只需為圖表添加標簽,如下所示:

networkx.draw(graph, node_positions, with_labels = True)

您也可以直接使用draw_spring而不必顯式分配節點位置:

networkx.draw_spring(graph, with_labels = True)

下圖顯示了運行以下代碼的結果:

import networkx as nx
G = nx.erdos_renyi_graph(10,0.4)
nx.draw(G, with_labels=True)
plt.show()

您的問題是您發送了圖形節點列表,而不是它期望 dict 的可選參數。 通過使用這個可選參數,networkx 允許您顯示您想要的任何標簽。 在您的情況下,您只需要節點名稱的明顯標簽。 這是默認行為。 就這么簡單

networkx.draw_networkx_labels(graph,node_positions,font_size=16)

就足夠了。 不要發送字典,它將使用節點名稱來標記它們。

另一種選擇是完全按照 abdallah 的建議進行操作,並使用with_labels=True選項在一個networkx.draw命令中繪制整個圖形。


對您的問題格式的簡要評論

當我最初閱讀您的問題時,我認為draw_networkx_labels命令給出的輸出與您的預期不同。

現在我已經嘗試了你的代碼,我發現它實際上給出了一個錯誤。 告訴我們錯誤是

AttributeError: 'list' 對象沒有屬性 'items'

會更容易找出問題所在,因此如果您收到錯誤消息,以供將來參考,它包含有關問題所在的信息。 如果您發布問題,請同時發布錯誤消息。

暫無
暫無

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

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