Python中的Networkx - 将节点属性绘制为节点外的标签

Mas*_*ood 11 python networkx

我有一个具有特定属性的节点图,我想在Python中通过networkx绘制图形,其中有几个属性作为节点外节点的标签.

有人可以帮助我如何编写我的代码来实现这一目标?

我的代码中有一个循环生成"interface_?" 防火墙列表中每个输入的属性(fwList)

for y in fwList:
    g.add_node(n, type='Firewall')
    print 'Firewall ' + str(n) + ' :' 
    for x in fwList[n]:
        g.node[n]['interface_'+str(i)] = x
        print 'Interface '+str(i)+' = '+g.node[n]['interface_'+str(i)]
        i+=1
    i=1
    n+=1
Run Code Online (Sandbox Code Playgroud)

然后,我稍后绘制节点和边缘,如:

pos=nx.spring_layout(g)
nx.draw_networkx_edges(g, pos)
nx.draw_networkx_nodes(g,pos,nodelist=[1,2,3],node_shape='d',node_color='red')
Run Code Online (Sandbox Code Playgroud)

并将稍后将其扩展到一些具有其他形状和颜色的新节点.

为了标记我在代码下面尝试的单个属性,但它没有用

labels=dict((n,d['interface_1']) for n,d in g.nodes(data=True))
Run Code Online (Sandbox Code Playgroud)

为了将文本放出节点,我不知道......

Ari*_*ric 9

您可以访问'pos'字典中的节点位置.因此,您可以使用matplotlib将文本放在任何您喜欢的位置.例如

In [1]: import networkx as nx

In [2]: G=nx.path_graph(3)

In [3]: pos=nx.spring_layout(G)

In [4]: nx.draw(G,pos)

In [5]: x,y=pos[1]

In [6]: import matplotlib.pyplot as plt

In [7]: plt.text(x,y+0.1,s='some text', bbox=dict(facecolor='red', alpha=0.5),horizontalalignment='center')
Out[7]: <matplotlib.text.Text at 0x4f1e490>
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


goz*_*lli 7

除了Aric的答案外,pos字典还包含x, y值中的坐标。因此,您可以对其进行操作,例如:

pos_higher = {}
y_off = 1  # offset on the y axis

for k, v in pos.items():
    pos_higher[k] = (v[0], v[1]+y_off)
Run Code Online (Sandbox Code Playgroud)

然后以新位置绘制标签:

nx.draw_networkx_labels(G, pos_higher, labels)
Run Code Online (Sandbox Code Playgroud)

G您的图形对象和labels字符串列表在哪里。


sci*_*ign 5

我喜欢创建一个nudge将布局移动一定偏移量的函数。

import networkx as nx
import matplotlib.pyplot as plt

def nudge(pos, x_shift, y_shift):
    return {n:(x + x_shift, y + y_shift) for n,(x,y) in pos.items()}

G = nx.Graph()
G.add_edge('a','b')
G.add_edge('b','c')
G.add_edge('a','c')

pos = nx.spring_layout(G)
pos_nodes = nudge(pos, 0, 0.1)                              # shift the layout

fig, ax = plt.subplots(1,2,figsize=(12,6))
nx.draw_networkx(G, pos=pos, ax=ax[0])                      # default labeling
nx.draw_networkx(G, pos=pos, with_labels=False, ax=ax[1])   # default nodes and edges
nx.draw_networkx_labels(G, pos=pos_nodes, ax=ax[1])         # nudged labels
ax[1].set_ylim(tuple(i*1.1 for i in ax[1].get_ylim()))      # expand plot to fit labels
plt.show()
Run Code Online (Sandbox Code Playgroud)

三角形中三个节点的两个并排图形表示。 左边的标签按照网络默认值直接放置在节点上,右边的标签稍微向上移动