Networkx:绘制边缘某些属性

时间:2014-12-15 20:51:43

标签: python graph

使用Networkx,我正在考虑一个实际上是几个子图的并集的图。我试图找出解决这个问题的最佳方法。目前,我一直在使用以下策略,但想知道是否有人有更好的建议。

首先,我一次添加一个节点,它们来自一个有m行和n列的矩形网格,所以它很容易。

G=nx.Graph()
PN = set() #first set of nodes
DN = set() #second set of nodes

for i in range(m):
    for j in range(n):
        if <sorting criterion here>:
            G.add_node(j + i *n, pos = <insert function of i and j here>, 
                       node_type = 'type_1', node_color = 'b')
            PN.add(j + i *n, pos = <insert function of i and j here> )
        else:
            G.add_node(j + i *n, pos = <insert function of i and j here>, 
                        node_type = 'type_2', node_color = 'g')
            DN.add(j + i *n, pos = <insert function of i and j here> )

pos = nx.get_node_attributes(G, 'pos')
nx.draw_networkx_nodes(G,pos,PN, node_color = 'b', node_size = 35)
nx.draw_networkx_nodes(G,pos,DN, node_color = 'g', node_size = 35)

我已经尝试过,但它失败了,做一些我认为会更好的类似事情。这个想法如下:

G=nx.Graph()
V = set()

for i in range(m):
    for j in range(n):
        if <sorting criterion here>:
            V.add(j + i *n, pos = <insert function of i and j here>, 
                  node_type = 'type 1', node_color = 'b')
        else:
            V.add(j + i *n, pos = <insert function of i and j here>, 
                  node_type = 'type 2', node_color = 'g')

color = nx.get_node_attributes(G,'node_color')
pos = nx.get_node_attributes(G, 'pos')
nx.draw_networkx_nodes(G,pos, color)

不幸的是,“color”似乎不像“pos”那样工作,后一种方法输出所有红色节点。任何建议将不胜感激!

1 个答案:

答案 0 :(得分:1)

你是对的 - 'node_color'参数采用单一颜色或颜色列表(不是字典)。因此,最简单的方法是使用与第一个代码段相同的策略,并分别绘制两组节点。

如果您只想对nx.draw_networkx_nodes()发出一次调用,则node_color参数应该有一个颜色列表,其长度与节点列表的长度相同,顺序相同。所以你可以做到以下几点:

color = nx.get_node_attributes(G,'node_color')
pos = nx.get_node_attributes(G, 'pos')
nodelist,node_color = zip(*color.items())
nx.draw_networkx_nodes(G,pos, nodelist=nodelist, node_color=node_color)