目前,我有一个基于度中心度来更改节点颜色和大小的NetworkX图,但我希望不是基于度中心度来更改颜色,而是基于模块化来更改节点的颜色,最好是在计算模块化时使用标签传播。
我尝试了更改颜色的方法,就像我在代码中根据度数中心度进行更改一样,但只得到了错误,因为度数中心度有多个值,而模块性只有一个值。
预期的结果是让节点的颜色根据模块性而不是度中心性而变化,同时保持节点的大小基于度中心性。
此处提供了此项目中使用的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()发布于 2021-04-29 15:47:00
我解决了这个问题。这就是答案
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()https://stackoverflow.com/questions/67295275
复制相似问题