Change Color & Size of graph in networkx based on degree centrality measure

Viewed 878

what I am trying to do is to calculate degree centrality using the NetworkX library, and then change the color and sizes of the different nodes based upon this measure.

The expected result would be to have the nodes show as different colors and sizes depending on their degree centrality, but currently, they only show the default color as I have no clue what I am supposed to do this.

The csv file I use in this project is available here. https://www.mediafire.com/file/q0kziy9h251fcjf/nutrients.csv/file

The file currently has no error messages, other than that the colors sizes do not change.

I've currently tried thinking of doing some sort of list comprehension to maybe sort the problem out, but I am yet unsure how to do so, or how to set up the color map(what colors is not important)

here is the code that I am using currently.

import networkx as nx
import matplotlib.pyplot as plt

Data = open('nutrients.csv', "r")
next(Data, None)
Graph_type = nx.Graph()

G = nx.parse_edgelist(Data, delimiter=',', create_using=Graph_type,
                      nodetype=str, data=(('weight', float),))


deg_centrality = nx.degree_centrality(G)
print(deg_centrality)


pos = nx.spring_layout(G)
nx.draw(G, pos)
plt.show()

H

2 Answers

How about something like this?

nutrients graph

import numpy as np
import matplotlib.colors as mcolors
import matplotlib.cm as cm

cent = np.fromiter(deg_centrality.values(), float)
sizes = cent / np.max(cent) * 200
normalize = mcolors.Normalize(vmin=cent.min(), vmax=cent.max())
colormap = cm.viridis

scalarmappaple = cm.ScalarMappable(norm=normalize, cmap=colormap)
scalarmappaple.set_array(cent)

plt.colorbar(scalarmappaple)
nx.draw(G, pos, node_size=sizes, node_color=sizes, cmap=colormap)
plt.show()

I introduced a somewhat arbitrary scaling factor that you can adjust to create other sizes. Numpy is used for convenient scaling but you could do the same with vanilla Python.

The color map can be changed to anything you like: https://matplotlib.org/stable/tutorials/colors/colormaps.html

EDIT: I managed to create a color gradient legend by adapting this answer.

This is a simple code with the drawing function of networkx:

import networkx as nx
import matplotlib.pyplot as plt
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)
# plot
pos = nx.kamada_kawai_layout(G)
nx.draw(G, pos, node_color=centrality, node_size=centrality*2e3)
nx.draw_networkx_labels(G, pos)
plt.show()

Output: enter image description here

I would highly recommend using plotly (see exemple) in order to have interaction. For this kind of graph I find it really useful.

Related