[英]How to change color of nodes in networkx graph based on graph's modularity
Currently, i have a NetworkX graph that changes color and size of nodes based on degree centrality, but I am looking to instead of changing color based on degree centrality, I am looking to change the color of the nodes based on modularity, preferably using label propagation in the calculation of the modularity.目前,我有一个 NetworkX 图,它可以根据度中心性更改节点的颜色和大小,但我希望不是根据度中心性更改颜色,而是希望根据模块性更改节点的颜色,最好使用 label模块化计算中的传播。
I've tried changing the color the same way I did on the code that changes according to degree centrality, but only getting errors as the degree centrality had multiple values and the modularity was one single value.我尝试以与根据度数中心性更改的代码相同的方式更改颜色,但由于度数中心性具有多个值并且模块化是一个值,因此只会出现错误。
The expected result is to have the color of the nodes change depending on modularity instead of degree centrality, while keeping the size of the nodes based on degree centrality.预期的结果是使节点的颜色根据模块性而不是度中心性而改变,同时根据度中心性保持节点的大小。
the CSV file used in this project is available here: https://www.mediafire.com/file/q0kziy9h251fcjf/nutrients.csv/file此项目中使用的 CSV 文件可在此处获得: https://www.mediafire.com/file/q0kziy9h251fcjf/nutrients.csv/file
Here is the code for the project这是项目的代码
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()
I fixed the problem.我解决了这个问题。 here is the answer
这是答案
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.