简体   繁体   English

如何在Networkx图形图中确定所选节点的特定颜色和大小

[英]How to determine specific color and size of chosen nodes in Networkx graph plot

I have the following code 我有以下代码

#!/usr/bin/python

import sys
import networkx as nx
import matplotlib.pyplot as plt

G = nx.Graph();
G.add_node('A')
G.add_node('B')
G.add_node('C')
G.add_node('D')
G.add_edge('A','B',weight=1)
G.add_edge('C','B',weight=1)
G.add_edge('B','D',weight=30)

colors=range(20)
nx.draw_spring(G,font_size=20,width=2,node_size=1000,node_color='#A0CBE2')
plt.savefig("/Users/handsomeguy/Desktop/test.png",dpi=300)

That generate the following graph (without the comment of course): 这会生成以下图表(当然没有评论): 在此输入图像描述

As stated in the picture above. 如上图所示。 I'd like to change the color of node C and D and enlarge the size of these chosen nodes. 我想改变节点CD的颜色,并扩大这些选定节点的大小。 How can I achieve that? 我怎样才能做到这一点?

Note that C and D are predetermined nodes by me the user. 注意,C和D是用户的预定节点。

One easy way to change the style of individual nodes when you have a small graph is to pass the parameters (eg node_size or node_color ) of networkx.draw_spring lists of sizes/colors. 当您拥有一个小图时,一种简单的方法来更改单个节点的样式是传递networkx.draw_spring大小/颜色列表的参数(例如node_sizenode_color )。 The trick is that if you use a list, the list has to include a size/color for each node , and the list has to be in the same order as the G.nodes() (hence why I sort the nodes in the example below): 诀窍是,如果使用列表,列表必须包含每个节点的大小/颜色,列表必须与G.nodes()顺序相同(因此我为什么要sort示例中的节点进行sort下面):

nx.draw_spring(G, nodelist=sorted(G.nodes()), font_size=20, width=2,
               node_size=[1000, 1000, 2000, 3000],
               node_color=["#A0CBE2", "#A0CBE2", "#FF0000", "#FFFF00"])

And here's the result: 这是结果:

示例图

Another option is to is to first store the layout of the nodes/edges for your graph, and then use networkx.draw_networkx . 另一个选择是首先存储图形的节点/边的布局,然后使用networkx.draw_networkx This is probably more useful when you have a large graph and only want to change the style for a few nodes. 当您拥有一个大图并且只想更改几个节点的样式时,这可能更有用。 Here, I first store the spring layout for the graph in pos , and then pass pos to draw each of the nodes and their edges: 在这里,我首先在pos存储图形的弹簧布局,然后传递pos以绘制每个节点及其边缘:

pos = nx.spring_layout(G)
nx.draw_networkx(G, pos=pos, nodelist=["A", "B"], node_size=1000, node_color='#A0CBE2', font_size=20, width=2)
nx.draw_networkx(G, pos=pos, nodelist=["C"], node_size=2000, node_color='#FF0000', font_size=20, width=2,)
nx.draw_networkx(G, pos=pos, nodelist=["D"], node_size=3000, node_color='#FFFF00', font_size=20, width=2)

Note : to turn off the axis in the networkx.draw_networkx plot, add the following command before plt.show() : 注意 :要关闭networkx.draw_networkx图中的轴,请在plt.show()之前添加以下命令:

limits=plt.axis('off') 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM