首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python Netgraph交互式标签

Python Netgraph交互式标签
EN

Stack Overflow用户
提问于 2020-10-07 21:03:10
回答 1查看 855关注 0票数 1

我试图创建一个互动的情节,使用网络和networkx。

我希望这个图允许节点的移动,并且当节点移动时,边和edge_labels也会动态更新。

移动节点是由网络here的作者解决的。现在,当我做了一个简单的情节,并试图标记一个边缘,标签保持静态,有时甚至不在边缘。

似乎处理edge_positions类似于最后两行的node_positions,至少应该解决标签不移动的问题。为什么标签没有固定在一个特定的边缘仍然令人费解。有没有人知道是否可以达到预期的效果?

在移动任何东西之前,这里有一个片段:

下面是将右下角节点移至左上角后的一个片段:

以下是我的当前代码:

代码语言:javascript
运行
复制
import matplotlib.pyplot as plt
import networkx as nx
import netgraph # pip install netgraph

#Graph creation:
G=nx.Graph(type="")

for i in range(6):
     G.add_node(i,shape="o")

#Changing shape for two nodes
G.nodes[1]['shape'] = "v"
G.nodes[5]['shape'] = "v"

#Add edges
G.add_edge(1,2)
G.add_edge(4,5)
G.add_edge(0,4)
G.add_edge(2,3)
G.add_edge(2,4)

labs={(1,2):"1 to 2"}

nx.draw_networkx_edge_labels(G, pos=nx.spring_layout(G),edge_labels=labs)
#Get node shapes
node_shapes = nx.get_node_attributes(G,"shape")


# Create an interactive plot.
# NOTE: you must retain a reference to the object instance!
# Otherwise the whole thing will be garbage collected after the initial draw
# and you won't be able to move the plot elements around.

pos = nx.layout.spring_layout(G)

######## drag nodes around #########

# To access the new node positions:
plot_instance =   netgraph.InteractiveGraph(G, node_shape=node_shapes, node_positions=pos, edge_positions=pos)


node_positions = plot_instance.node_positions
edge_positions = plot_instance.edge_positions

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-09 10:27:50

要将其作为正式答案,需要向InteractiveGraph对象添加要绘制(并移动)边缘标签的信息,即:

代码语言:javascript
运行
复制
netgraph.InteractiveGraph(G, 
                          node_shape=node_shapes, 
                          node_positions=pos, 
                          edge_positions=pos, 
                          edge_labels=labs)

(强调最后一个参数)

正如您已经注意到的,您不需要调用nx.draw_networkx_edge_labels

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64252279

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档