簡體   English   中英

如何根據圖的模塊化改變networkx圖中節點的顏色

[英]How to change color of nodes in networkx graph based on graph's modularity

目前,我有一個 NetworkX 圖,它可以根據度中心性更改節點的顏色和大小,但我希望不是根據度中心性更改顏色,而是希望根據模塊性更改節點的顏色,最好使用 label模塊化計算中的傳播。

我嘗試以與根據度數中心性更改的代碼相同的方式更改顏色,但由於度數中心性具有多個值並且模塊化是一個值,因此只會出現錯誤。

預期的結果是使節點的顏色根據模塊性而不是度中心性而改變,同時根據度中心性保持節點的大小。

此項目中使用的 CSV 文件可在此處獲得: https://www.mediafire.com/file/q0kziy9h251fcjf/nutrients.csv/file

這是項目的代碼

import networkx as nx
import matplotlib.pyplot as plt
import networkx.algorithms.community as nx_com
import numpy as np

# create graph from data
with open("nutrients.csv", "r") as f:
    G = nx.parse_edgelist(f.readlines(), delimiter=",")

# centrality
deg_centrality = nx.degree_centrality(G)
centrality = np.fromiter(deg_centrality.values(), float)

# modularity
mod = nx_com.modularity(G, nx_com.label_propagation_communities(G))

# plot
pos = nx.spring_layout(G)
nx.draw(G, pos, node_color=centrality, node_size=centrality*2e3)
nx.draw_networkx_labels(G, pos)
plt.show()

我解決了這個問題。 這是答案

import networkx as nx
import matplotlib.pyplot as plt
import networkx.algorithms.community as nx_com
import numpy as np
import community as community_louvain

# create graph from data
with open("nutrients.csv", "r") as f:
    G = nx.parse_edgelist(f.readlines(), delimiter=",")

# centrality
deg_centrality = nx.degree_centrality(G)
centrality = np.fromiter(deg_centrality.values(), float)

# modularity
label = community_louvain.best_partition(G)
mod = community_louvain.modularity(label, G)
values = [label.get(node) for node in G.nodes()]


# plot
pos = nx.spring_layout(G)
nx.draw(G, pos, node_color=values, node_size=centrality*2e3)
nx.draw_networkx_labels(G, pos)
plt.show()

暫無
暫無

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

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