简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM