且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

根据节点值为networkx中的节点绘制不同的颜色

更新时间:2023-01-28 12:01:57

  import networkx as nx 
import numpy as np
import matplotlib.pyplot as plt

G = nx.Graph()
G.add_edges_from(
[( '','B'),('A','C'),('D','B'),('E','C'),('E','F'),$ ('B','H'),('B','G'),('B','F'),('C','G')])

val_map = {'A':1.0,
'D':0.5714285714285714,
'H':0.0}

values = [val_map.get(node,0.25)为节点在G.nodes()]

nx.draw(G,cmap = plt.get_cmap('jet'),node_color = values)
plt.show()

产生






数字在 values 中与 G.nodes()中的节点关联。
也就是说, values 中的第一个数字与 G.nodes()$ c $中的第一个节点关联c>,类似的第二个,等等。


I have a large graph of nodes and directed edges. Furthermore, I have an additional list of values assigned to each node.

I now want to change the color of each node according to their node value. So e.g., drawing nodes with a very high value red and those with a low value blue (similar to a heatmap). Is this somehow easily possible to achieve? If not with networkx, I am also open for other libraries in Python.

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

G = nx.Graph()
G.add_edges_from(
    [('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'),
     ('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')])

val_map = {'A': 1.0,
           'D': 0.5714285714285714,
           'H': 0.0}

values = [val_map.get(node, 0.25) for node in G.nodes()]

nx.draw(G, cmap=plt.get_cmap('jet'), node_color=values)
plt.show()

yields


The numbers in values are associated with the nodes in G.nodes(). That is to say, the first number in values is associated with the first node in G.nodes(), and similarly for the second, and so on.