【问题标题】:Python Netgraph Interactive LabelsPython Netgraph 交互式标签
【发布时间】:2021-01-22 21:30:31
【问题描述】:

我正在尝试使用 netgraph 和 networkx 创建交互式绘图。

我希望绘图允许节点移动,并且随着节点的移动,edges 和 edge_labels 也会动态更新。

netgraph 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

【问题讨论】:

  • 由于我没有安装netgraph,仅作为评论:netgraph.InteractiveGraph(G, node_shape=node_shapes, node_positions=pos, edge_positions=pos, edge_labels=labs) 是否解决了您的问题?
  • 我不得不删除:nx.draw_networkx_edge_labels(G, pos=nx.spring_layout(G),edge_labels=labs) 并对这一行进行了建议的更改:netgraph.InteractiveGraph(G, node_shape=node_shapes , node_positions=pos, edge_positions=pos, edge_labels=labs) 现在这给了我沿边缘的 edge_labels。谢谢@Sparky05。现在,我该如何评价你的答案?
  • 很高兴它的工作:) 我现在只是创建了一个完整的答案,如果你愿意,你可以接受和投票。

标签: python networkx digraphs


【解决方案1】:

要将其作为正式答案,您需要将要绘制(和移动)边缘标签的信息添加到 InteractiveGraph 对象,即以下内容

netgraph.InteractiveGraph(G, 
                          node_shape=node_shapes, 
                          node_positions=pos, 
                          edge_positions=pos, 
                          edge_labels=labs)

(强调最后一个参数)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 2015-08-20
    • 2016-09-14
    • 2021-09-15
    • 2011-12-19
    • 1970-01-01
    相关资源
    最近更新 更多