根据节点值为 networkx 中的节点绘制不同的颜色 [英] Draw different color for nodes in networkx based on their node value

查看:190
本文介绍了根据节点值为 networkx 中的节点绘制不同的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大的节点图和有向边.此外,我还有一个分配给每个节点的附加值列表.

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

我现在想根据节点值更改每个节点的颜色.因此,例如,绘制具有非常高值红色的节点和具有低值蓝色的节点(类似于热图).这是否很容易实现?如果没有 networkx,我也对 Python 中的其他库开放.

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('viridis'), node_color=values, with_labels=True, font_color='white')
plt.show()

收益

values 中的数字与 G.nodes() 中的节点相关联.也就是说,values 中的第一个数字与 G.nodes() 中的第一个节点相关联,第二个类似,依此类推.

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.

这篇关于根据节点值为 networkx 中的节点绘制不同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆