如何解决Python Netgraph交互式标签
我正在尝试使用netgraph和networkx创建一个交互式图。
我希望绘图允许节点移动,并且随着节点移动,edge和edge_labels也将动态更新。
移动节点已由网图here的作者解决。现在,当我绘制一个简单的图并尝试标记一条边时,该标签保持静态,有时甚至不在一条边上。
在最后两行上,处理类似于node_positions的edge_positions似乎至少应该解决标签未移动的问题。为什么标签没有固定到特定边缘仍然令人困惑。有谁知道是否可以达到预期的效果?
在移动任何东西之前,这里是一个片段:
将右下角的节点移到左上角后,这是一个片段:
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
解决方法
要将其作为正式答案,您需要向InteractiveGraph
对象添加要绘制(和移动)边缘标签的信息,即以下内容
netgraph.InteractiveGraph(G,node_shape=node_shapes,node_positions=pos,edge_positions=pos,edge_labels=labs)
(强调最后一个参数)
您已经注意到,那么您不需要致电nx.draw_networkx_edge_labels
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。