Networkx 传播节点和短缺标签
Networkx spread nodes and shorten lables
我有一个网络二分图。
这是代码:
G = nx.Graph()
G.add_nodes_from(USsNames, bipartite=0) # Add the node attribute "bipartite"
G.add_nodes_from(TCsNames, bipartite=1)
G.add_weighted_edges_from(compoundArr)
labeldict = {}
# Separate by group
pos = {}
# Update position for node from each group
pos.update({node: [1, index] for index, node in enumerate(USsNames)})
pos.update({node: [2, index] for index, node in enumerate(TCsNames)})
nx.draw(G, pos, node_size=10,with_labels=False)
for p in pos: # raise text positions
pos[p][1] += 0.12
# create the dictionary with the formatted labels
edge_labels = {i[0:2]:'{0:.2f}'.format(i[2]['weight']) for i in G.edges(data=True)}
# add the custom egde labels
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels,font_size=8)
nx.draw_networkx_labels(G, pos,font_size=8)
plt.show()
以及输出:
我需要展开左侧节点以便它们展开,并缩短右侧节点标签(假设前四个字符)。
我试图找到解决方案,但没有成功。谢谢。
我根据生成的示例数据重建了您的案例。
首先我们有这张图。
左数组的大小远小于右数组的大小,所以左数组是不按比例绘制的。要正确绘制它,您应该修改您的位置更新功能:
pos.update({node: [1, index] for index, node in enumerate(USsNames)})
我们知道 TCsNames
大于 USsNames
因此我们可以将每个 USsNames
节点的 Y 位置乘以它们的比率:
pos.update({node: [1, index*(len(TCsNames)/len(USsNames))] for index, node in enumerate(USsNames)})
现在我们有了这张图:
要裁剪节点标签,您应该使用 labels
参数修改您的 draw_networkx_labels
:
nx.draw_networkx_labels(G, pos, labels=node_labels, font_size=8)
其中 node_labels
等于:
node_labels = {i: i[:5] for i in G.nodes}
(5是期望的节点标签长度)。
我们终于有了您需要的图表:
我有一个网络二分图。 这是代码:
G = nx.Graph()
G.add_nodes_from(USsNames, bipartite=0) # Add the node attribute "bipartite"
G.add_nodes_from(TCsNames, bipartite=1)
G.add_weighted_edges_from(compoundArr)
labeldict = {}
# Separate by group
pos = {}
# Update position for node from each group
pos.update({node: [1, index] for index, node in enumerate(USsNames)})
pos.update({node: [2, index] for index, node in enumerate(TCsNames)})
nx.draw(G, pos, node_size=10,with_labels=False)
for p in pos: # raise text positions
pos[p][1] += 0.12
# create the dictionary with the formatted labels
edge_labels = {i[0:2]:'{0:.2f}'.format(i[2]['weight']) for i in G.edges(data=True)}
# add the custom egde labels
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels,font_size=8)
nx.draw_networkx_labels(G, pos,font_size=8)
plt.show()
以及输出:
我需要展开左侧节点以便它们展开,并缩短右侧节点标签(假设前四个字符)。
我试图找到解决方案,但没有成功。谢谢。
我根据生成的示例数据重建了您的案例。
首先我们有这张图。
左数组的大小远小于右数组的大小,所以左数组是不按比例绘制的。要正确绘制它,您应该修改您的位置更新功能:
pos.update({node: [1, index] for index, node in enumerate(USsNames)})
我们知道 TCsNames
大于 USsNames
因此我们可以将每个 USsNames
节点的 Y 位置乘以它们的比率:
pos.update({node: [1, index*(len(TCsNames)/len(USsNames))] for index, node in enumerate(USsNames)})
现在我们有了这张图:
要裁剪节点标签,您应该使用 labels
参数修改您的 draw_networkx_labels
:
nx.draw_networkx_labels(G, pos, labels=node_labels, font_size=8)
其中 node_labels
等于:
node_labels = {i: i[:5] for i in G.nodes}
(5是期望的节点标签长度)。
我们终于有了您需要的图表: