带绘图的网络图

2024-10-01 07:13:08 发布

您现在位置:Python中文网/ 问答频道 /正文

通过教程学习绘制python图形: https://plot.ly/ipython-notebooks/network-graphs/

由于Nodes只能以数字的形式工作(如果m错误,则执行correct),因此我将具有G2dd2b1482072125的节点替换为1,并进行反向映射以在以后的图形点使用

import plotly.plotly as py
from plotly.graph_objs import *
import networkx as nx

node_to_nmbr_dict = {
    'G2dd2b1482072125': 1,
    'G2dd2b1482072126': 2,
    'G2dd2b1482072127': 3
}
nmbr_to_node_dict = {
    1: 'G2dd2b1482072125',
    2: 'G2dd2b1482072126',
    3: 'G2dd2b1482072127'
}

# create Graph object, with nodes = len(nmbr_to_node_dict), (i think!!)
G=nx.random_geometric_graph(len(nmbr_to_node_dict),1)

edge_list = [(1, 2), (2, 3), (3, 1)]

# Remove default edges created automatically
G.remove_edges_from(G.edges())

#add your own edges
G.add_edges_from(edge_list)

# Store position as node attribute data for random_geometric_graph and find node near center (0.5, 0.5)
pos=nx.get_node_attributes(G,'pos')

dmin=1
ncenter=0
for n in pos:
    x,y=pos[n]
    d=(x-0.5)**2+(y-0.5)**2
    if d<dmin:
        ncenter=n
        dmin=d

        p=nx.single_source_shortest_path_length(G,ncenter)

# Add edges as disconnected lines in a single trace and nodes as a scatter trace        
edge_trace = Scatter(
    x=[], 
    y=[], 
    line=Line(width=0.5,color='#888'),
    hoverinfo='none',
    mode='lines')

for edge in G.edges():
    x0, y0 = G.node[edge[0]]['pos']
    x1, y1 = G.node[edge[1]]['pos'] # <----- This here throws keys error
    edge_trace['x'] += [x0, x1, None]
    edge_trace['y'] += [y0, y1, None] 

KeyError               Traceback (most recent call last)
<ipython-input-96-077055af3467> in <module>()
      1 for edge in G.edges():
      2     x0, y0 = G.node[edge[0]]['pos']
----> 3     x1, y1 = G.node[edge[1]]['pos']
      4     edge_trace['x'] += [x0, x1, None]
      5     edge_trace['y'] += [y0, y1, None]

KeyError: 'pos'        

我的要求与上面的教程中提到的完全相同,node_info将有我的G2dd2b1482072125值,这些值已经用dicts中的数字进行了反向映射node_to_nmbr_dict

有人能指出我在绘制图表时到底哪里出了问题?在


定期倾倒区:

^{pr2}$

Tags: toinposnodeforastracedict
1条回答
网友
1楼 · 发布于 2024-10-01 07:13:08

您有一个由nx.random_geometric_graph编号引起的“off by one”错误 节点从0开始,而您的edge_list(显然)从1开始编号节点。在

例如

In [80]: G = nx.random_geometric_graph(3, 1)

In [81]: G.nodes()
Out[81]: [0, 1, 2]

到目前为止,还不错。每个节点都有一个pos

^{pr2}$

哎呀!现在引入了一个新节点3,但没有pos

In [86]: G.nodes(data=True)
Out[86]: 
[(0, {'pos': [0.3530839410903017, 0.6066802744128065]}),
 (1, {'pos': [0.8770904947229078, 0.642494748842952]}),
 (2, {'pos': [0.286083277031809, 0.2958147129607025]}),
 (3, {})]

因此,G.node[edge[1]]['pos']可以在edge[1]为3时引发KeyError。在


您的代码可以通过从edge_list中的每个节点值中减去1来修复(从而将节点重新编号为从0开始):

edge_list = [(0, 1), (1, 2), (2, 0)]

相关问题 更多 >