如何在Python networkx中的节点名称旁边添加节点属性?

时间:2018-08-15 19:13:33

标签: python networkx labels

我想画一个连接同事和电影偏好的二分图。如何在图形中同时显示节点中的节点名称(即电影名称或同事名称)和节点属性(无论是同事还是电影)?

我当前的代码仅显示节点属性,并删除节点名称。

我的代码:

BG = nx.Graph()
BG.add_nodes_from(employees, bipartite=0, _type='employee')
BG.add_nodes_from(movies, bipartite=1, _type='movie')
edgeinfo = pd.read_csv('Employee_Movie_Choices.txt', sep='\t')
edges = [tuple(x) for x in edgeinfo.values]
BG.add_edges_from(edges)

labels = dict((n,d['_type']) for n,d in BG.nodes(data=True))

%matplotlib notebook
import matplotlib.pyplot as plt

plt.figure()
pos = nx.spring_layout(BG)
edges = BG.edges()
nx.draw_networkx(BG, pos, edges=edges, labels=labels)

如果我创建标签元组,他会给我一个错误:

BG = nx.Graph()
BG.add_nodes_from(employees, bipartite=0, _type='employee')
BG.add_nodes_from(movies, bipartite=1, _type='movie')
edgeinfo = pd.read_csv('Employee_Movie_Choices.txt', sep='\t')
edges = [tuple(x) for x in edgeinfo.values]
BG.add_edges_from(edges)

labels = dict((n,d['_type']) for n,d in BG.nodes(data=True))  ###ik krijg hier naam movie en employee niet meer bij !!!
labels_new = [(k, v) for k, v in labels.items()]
#labels = [tuple(n,d['_type']) for n, d in BG.nodes(data=True)]
#nx.draw(BG, labels=labels)

%matplotlib notebook
import matplotlib.pyplot as plt

plt.figure()
pos = nx.spring_layout(BG)
edges = BG.edges()
nx.draw_networkx(BG, pos, edges=edges, labels=labels_new)

错误: ---> nx.draw_networkx(BG,pos,edge = edges,labels = labels_new) AttributeError:“列表”对象没有属性“项目”

1 个答案:

答案 0 :(得分:1)

为什么会出现错误

摘自draw_networkx的文档 ,labels必须是字典,而您输入的labels_new是列表。

  

标签(字典,可选(默认=无))–节点中的节点标签   用文本标签节点作为关键字的字典

根据您的代码

  

labels_new = [[k,v)for labels,items()中的k,v]

因此,出现错误AttributeError: 'list' object has no attribute 'items'

解决方法:自定义labels字典

我没有数据,但是可以快速破解

labels = dict((n, "(" + n + "," + d['_type'] + ")") for n,d in BG.nodes(data=True))

演示

import networkx as nx
from networkx.algorithms import bipartite
%matplotlib notebook
import matplotlib.pyplot as plt

BG = nx.Graph()
employees = [str(i) for i in range(3)]
movies = ["mA", "mB", "mC"]
BG.add_nodes_from(employees, bipartite=0, _type='emp')
BG.add_nodes_from(movies, bipartite=1, _type='mov')
edges = [("0", "mA"), ("0", "mC"), ("1", "mA"),("1", "mB"), ("2", "mA")]
BG.add_edges_from(edges)
labels = dict((n, "(" + n + "," + d['_type'] + ")") for n,d in BG.nodes(data=True))

# Setting up pos for drawing bipartite graph. See the reference for more info
X, Y = bipartite.sets(BG)
pos = dict()
pos.update( (n, (1, i)) for i, n in enumerate(X) ) # put nodes from X at x=1
pos.update( (n, (2, i)) for i, n in enumerate(Y) ) # put nodes from Y at x=2

plt.figure()
edges = BG.edges()
nx.draw_networkx(BG, pos, edges=edges, labels=labels)

enter image description here

参考

mdml's answer for drawing bipartite graph