Python 如何为 NetworkX 中的节点设置颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27030473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:21:17  来源:igfitidea点击:

How to set colors for nodes in NetworkX?

pythonnetworkx

提问by Gokhan Arik

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

我创建了我的图表,到目前为止一切看起来都很棒,但我想在创建后更新节点的颜色。

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.

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

If anyone is interested, sample code is available on Github

如果有人感兴趣,可以在Github上找到示例代码

采纳答案by Abdallah Sobehy

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:

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

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 imageenter image description here.

您将在附图中找到该图表在此处输入图片说明

回答by Montenegrodr

Refer to node_colorparameter:

参考node_color参数:

nx.draw_networkx_nodes(G, pos, node_size=200, node_color='#00b4d9')