Python NetworkX — set node color automatically based on a list of values

2024/10/11 14:22:21

I generated a graph with networkx

import networkx as nx  
s = 5
G = nx.grid_graph(dim=[s,s])
nodes = list(G.nodes)
edges = list(G.edges)
p = []
for i in range(0, s):for j in range(0, s):p.append([i,j])
for i in range(0, len(nodes)):G.nodes[nodes[i]]['pos'] = p[i]pos = {}
for i in range(0, len(nodes)):pos[nodes[i]] = p[i]nx.draw(G, pos)

enter image description here

Now I would like to assign a value to each node between 0 and 4

from random import randint
val = []
for i in range(0, len(G.nodes())):val.append(randint(0,4)) 

And I would like to assign the color to each node base on the val list and plot something like shown here

enter image description here

Answer

networkx.draw has the node_color, vmin, vmax and cmap parameters:

cmap (Matplotlib colormap, optional (default=None)) – Colormap for mapping intensities of nodes

vmin,vmax (float, optional (default=None)) – Minimum and maximum for node colormap scaling

node_color (color string, or array of floats, (default=’#1f78b4’)) – Node color. Can be a single color format string, or a sequence of colors with the same length as nodelist. If numeric values are specified they will be mapped to colors using the cmap and vmin,vmax parameters. See matplotlib.scatter for more details.

You can write a list in it so your nodes will be colored (for example):

colors = [i/len(G.nodes) for i in range(len(G.nodes))]
...
...
nx.draw(G, pos, node_color=colors)

enter image description here

https://en.xdnf.cn/q/69763.html

Related Q&A

control wspace for matplotlib subplots

I was wondering: I have a 1 row, 4 column plot. However, the first three subplots share the same yaxes extent (i.e. they have the same range and represent the same thing). The forth does not. What I w…

Getting indices of both zero and nonzero elements in array

I need to find the indicies of both the zero and nonzero elements of an array.Put another way, I want to find the complementary indices from numpy.nonzero().The way that I know to do this is as follows…

tweepy how to get a username from id

how do I derrive a plaintext username from a user Id number with tweepy? Here is the CORRECTED code that I am using:ids = [] userid = "someOne" for page in tweepy.Cursor(api.followers_ids, s…

How to select many to one to many without hundreds of queries using Django ORM?

My database has the following schema:class Product(models.Model):passclass Tag(models.Model):product = models.ForeignKey(Product)attr1 = models.CharField()attr2 = models.CharField()attr3 = models.CharF…

Quickly dumping a database in memory to file

I want to take advantage of the speed benefits of holding an SQLite database (via SQLAlchemy) in memory while I go through a one-time process of inserting content, and then dump it to file, stored to b…

QStatusBar message disappears on menu hover

I have a very basic QMainWindow application that contains a menubar and a statusbar. When I hover over the menu the status message disappears. More precisely, the status message is cleared. I have no i…

How to eliminate a python3 deprecation warning for the equality operator?

Although the title can be interpreted as three questions, the actual problem is simple to describe. On a Linux system I have python 2.7.3 installed, and want to be warned about python 3 incompatibiliti…

Cannot get scikit-learn installed on OS X

I cannot install scikit-learn. I can install other packages either by building them from source or through pip without a problem. For scikit-learn, Ive tried cloning the project on GitHub and installin…

Decompressing a .bz2 file in Python

So, this is a seemingly simple question, but Im apparently very very dull. I have a little script that downloads all the .bz2 files from a webpage, but for some reason the decompressing of that file is…

Why does Pandas coerce my numpy float32 to float64?

Why does Pandas coerce my numpy float32 to float64 in this piece of code:>>> import pandas as pd >>> import numpy as np >>> df = pd.DataFrame([[1, 2, a], [3, 4, b]], dtype=np…