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

如何在Python networkx中在节点名称旁边添加节点属性?,python,networkx,labels,Python,Networkx,Labels,我想画一个连接同事和电影偏好的二分图。如何在图中同时显示节点名称(即moviename或同事名称)和节点属性(无论是同事还是电影) 我的当前代码仅显示节点属性并删除节点名称 我的代码: 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('Emp

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

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

我的代码:

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.绘制网络x(背景、位置、边=边、标签=标签\u新)
AttributeError:“list”对象没有属性“items”

出现错误的原因

根据 ,
labels
需要是一个字典,而您输入的
labels\u new
是一个列表

标签(字典,可选(默认值=无))–节点中的节点标签 由文本标签节点键入的字典

根据你的代码

labels_new=[(k,v)表示labels.items()中的k,v]

因此,出现错误
AttributeError:“list”对象没有属性“items”

解决方法:自定义
标签
字典

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

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)