如何在NetworkX中为节点设置颜色? [英] How to set colors for nodes in NetworkX?

查看:4632
本文介绍了如何在NetworkX中为节点设置颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了图形,到目前为止一切看起来都很不错,但是我想在创建后更新节点的颜色.

I created my graph, everything looks great so far, but I want to update color of my nodes after creation.

我的目标是可视化DFS,我将首先显示初始图形,然后在DFS解决问题时逐步显示颜色节点.

My goal is to visualize DFS, I will first show the initial graph and then color nodes step by step as DFS solves the problem.

如果有人感兴趣,可以在 Github

If anyone is interested, sample code is available on Github

推荐答案

您需要指定一个颜色映射,该颜色映射将颜色映射到每个节点并将其发送到nx.draw函数.澄清一下,对于20个节点,我想将前10个节点涂成蓝色,将其余10个涂成绿色.代码如下:

All you need is to specify a color map which maps a color to each node and send it to nx.draw function. To clarify, for a 20 node I want to color the first 10 in blue and the rest in green. The code will be as follows:

G = nx.erdos_renyi_graph(20, 0.1)
color_map = []
for node in G:
    if node < 10:
        color_map.append('blue')
    else: 
        color_map.append('green')      
nx.draw(G, node_color=color_map, with_labels=True)
plt.show()

您将在所附的图像中找到该图.

You will find the graph in the attached image.

这篇关于如何在NetworkX中为节点设置颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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