如何在网络的颜色图中设置最大值(Python) [英] How to set a maximum value in a color map of a network (Python)

查看:83
本文介绍了如何在网络的颜色图中设置最大值(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个 10 个节点的网络,节点值为 values = [i for i in range(len(10))]

Imagine you have a network of 10 nodes and the nodes value is values = [i for i in range(len(10))]

现在我想给这个网络着色,我只想要一个值小于 5 的节点的颜色图.我该怎么做?

Now I want to color this network however, I only want a color map of the nodes that have a value less than 5. How do I do this?

提前致谢.

推荐答案

为此,在 nx.draw 中绘图时,您可以简单地不包含(过滤掉)那些想要避免的节点.如果您确实想包含它们,尽管只是没有颜色图(可能是恒定颜色),只需使用恒定颜色而不是删除这些节点.这是使用随机图的示例:

For that, you can simply not include (filte out) those nodes you want to avoid when plotting in nx.draw. If you do want to include them, though just without a colormap (perhaps a constant color), just use a constant color rather than removing those nodes. Here's an example using a random graph:

import networkx as nx
import matplotlib as mpl
from matplotlib import pyplot as plt

G = nx.barabasi_albert_graph(10, 1)
# defines a colormap lookup table 
nodes = sorted(list(G.nodes()))
low, *_, high = sorted(values)
norm = mpl.colors.Normalize(vmin=low, vmax=high, clip=True)
mapper = mpl.cm.ScalarMappable(norm=norm, cmap=mpl.cm.coolwarm)

要包括所有节点,但让那些 <5 没有任何颜色图:

To include all nodes, but have those <5 without any colormap:

plt.subplots(figsize=(10,6))
nx.draw(G, 
        nodelist=values,
        node_size=500,
        node_color=[mapper.to_rgba(i) if i>5 else 'lightblue' 
                    for i in values], 
        with_labels=True)
plt.show()

直接删除它们:

plt.subplots(figsize=(10,6))

pos = nx.spring_layout(G)
nx.draw_networkx_edges(G, pos=pos)
nx.draw_networkx_nodes(G, pos=pos,
                       nodelist=[i for i in values if i>5],
                       node_color=[mapper.to_rgba(i) 
                            for i in nodes if i>5])
nx.draw_networkx_labels(G, pos=pos,
                       labels={node:node for node in nodes if node>5})

这篇关于如何在网络的颜色图中设置最大值(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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