Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在虚线/绘图仪中显示属性会导致KeyError_Python_Networkx - Fatal编程技术网

Python 在虚线/绘图仪中显示属性会导致KeyError

Python 在虚线/绘图仪中显示属性会导致KeyError,python,networkx,Python,Networkx,我试图将文档中的引用可视化。为此,我使用了Elements.csv,如下所示: Doc,Description,DocumentID SOP Laboratory,This SOP should be used in the lab,10414 Visual Design,Basics for Visual Design,1200139348 GMP,Good Manufacturing Practises,4638261 Windows PC manual,This manual descri

我试图将文档中的引用可视化。为此,我使用了
Elements.csv
,如下所示:

Doc,Description,DocumentID
SOP Laboratory,This SOP should be used in the lab,10414
Visual Design,Basics for Visual Design,1200139348
GMP,Good Manufacturing Practises,4638261
Windows PC manual,This manual describes how to use Windows PCs,271922
Connections.csv
中,我有以下参考资料:

Source,Target
SOP Laboratory,Windows PC manual
SOP Laboratory,GMP
Visual Design,Windows PC manual
也就是说,
SOP实验室
中有一个参考,指向
Windows PC手册
,等等

我用于可视化此网络的代码与Dash/Plotly一起工作:

import pandas as pd
import networkx as nx
import plotly.graph_objs as go
import plotly
import dash
import dash_core_components as dcc
import dash_html_components as html

## Dash setup

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)


## Data

edges = pd.read_csv('Connections.csv', encoding="utf8")
nodes = pd.read_csv('Elements.csv', encoding="utf8")


## Graph

G = nx.from_pandas_edgelist(edges, 'Source', 'Target')
nx.set_node_attributes(G, nodes.set_index('Doc')['Description'].to_dict(), 'Description')
nx.set_node_attributes(G, nodes.set_index('Doc')['DocumentID'].to_dict(), 'DocumentID')

pos = nx.spring_layout(G)

for node in G.nodes:
    G.nodes[node]['pos'] = list(pos[node])

traceRecode = []

index = 0
for edge in G.edges:
    x0, y0 = G.nodes[edge[0]]['pos']
    x1, y1 = G.nodes[edge[1]]['pos']
    trace = go.Scatter(x=tuple([x0, x1, None]), y=tuple([y0, y1, None]),
                        mode='lines',
                        hoverinfo='none',
                        line={'width': 2},
                        marker=dict(color='#000000'),
                        line_shape='spline',
                        opacity=1)
    traceRecode.append(trace)
    index = index + 1

node_trace = go.Scatter(
    x=[],
    y=[],
    hovertext=[],
    text=[],
    mode='markers+text',
    textposition="bottom center",
    hoverinfo='text',
    marker=dict(
        showscale=True,
        colorscale='Agsunset',
        reversescale=True,
        color=[],
        size=20,
        colorbar=dict(
            thickness=15,
            title='Node Connections',
            xanchor='left',
            titleside='right'
        ),
        line=dict(width=0)))

index = 0
for node in G.nodes():
    x, y = G.nodes[node]['pos']
    # hovertext = "Document Name: " + str(G.nodes[node]['Doc']) + "<br>" + "Document ID: " + str(G.nodes[node]['DocumentID'])
    # text = nodes['Doc'][index]
    node_trace['x'] += tuple([x])
    node_trace['y'] += tuple([y])
    # node_trace['hovertext'] += tuple([hovertext])
    # node_trace['text'] += tuple([text])
    index = index + 1

for node, adjacencies in enumerate(G.adjacency()):
    node_trace['marker']['color']+=tuple([len(adjacencies[1])])
    node_info = adjacencies[0] #+ ' (' +str(adjacencies[1]) + ')' #+' (' +str(len(adjacencies[1])) + ' connections)'
    node_trace['text']+=tuple([node_info])

traceRecode.append(node_trace)

figure = {
    "data": traceRecode,
    "layout": go.Layout(title='Document Overview', showlegend=False, hovermode='closest',
                        margin={'b': 40, 'l': 40, 'r': 40, 't': 40},
                        xaxis={'showgrid': False, 'zeroline': False, 'showticklabels': False},
                        yaxis={'showgrid': False, 'zeroline': False, 'showticklabels': False},
                        height=1000,
                        clickmode='event+select',
                        annotations=[
                            dict(
                                ax=(G.nodes[edge[0]]['pos'][0] + G.nodes[edge[1]]['pos'][0]) / 2,
                                ay=(G.nodes[edge[0]]['pos'][1] + G.nodes[edge[1]]['pos'][1]) / 2, axref='x', ayref='y',
                                x=(G.nodes[edge[1]]['pos'][0] * 3 + G.nodes[edge[0]]['pos'][0]) / 4,
                                y=(G.nodes[edge[1]]['pos'][1] * 3 + G.nodes[edge[0]]['pos'][1]) / 4, xref='x', yref='y',
                                showarrow=True,
                                arrowhead=4,
                                arrowsize=2,
                                arrowwidth=1,
                                opacity=1
                            ) for edge in G.edges]
                        )}

app.layout = html.Div([
    dcc.Graph(figure=figure
    ),
])

if __name__ == '__main__':
    app.run_server(debug=True)
将熊猫作为pd导入
将networkx导入为nx
导入plotly.graph_objs作为go
绘声绘色地导入
导入破折号
将仪表板核心组件作为dcc导入
将dash_html_组件导入为html
##破折号设置
外部_样式表=['https://codepen.io/chriddyp/pen/bWLwgP.css']
app=dash.dash(名称,外部样式表=外部样式表)
##资料
edges=pd.read\u csv('Connections.csv',encoding=“utf8”)
nodes=pd.read\u csv('Elements.csv',encoding=“utf8”)
##图表
G=nx.来自\u pandas\u edgelist(边、'源'、'目标')
nx.set_node_属性(G,nodes.set_index('Doc')['Description'])。设置为_dict(),'Description')
nx.set_node_属性(G,nodes.set_index('Doc')['DocumentID'])。设置为_dict(),'DocumentID')
位置=nx.弹簧布置图(G)
对于G.nodes中的节点:
G.nodes[node]['pos']=列表(pos[node])
traceRecode=[]
索引=0
对于G.边中的边:
x0,y0=G.nodes[edge[0]['pos']
x1,y1=G.节点[边[1]['pos']
trace=go.Scatter(x=tuple([x0,x1,None]),y=tuple([y0,y1,None]),
mode='lines',
hoverinfo='none',
行={'width':2},
marker=dict(颜色='#000000'),
直线形状='样条',
不透明度=1)
traceRecode.append(跟踪)
索引=索引+1
节点_trace=go.Scatter(
x=[],
y=[],
hovertext=[],
text=[],
mode='markers+text',
textposition=“底部中心”,
hoverinfo='text',
记号笔(
showscale=True,
色阶='AG日落',
反向刻度=真,
颜色=[],
尺寸=20,
色条(
厚度=15,
title='Node Connections',
xanchor='left',
标题旁边的“='right'
),
行=dict(宽度=0)))
索引=0
对于G.nodes()中的节点:
x、 y=G.nodes[node]['pos']
#hovertext=“文档名称:”+str(G.nodes[node]['Doc'])+”
“+”文档ID:“+str(G.nodes[node]['DocumentID'])) #text=节点['Doc'][索引] 节点跟踪['x']+=元组([x]) 节点跟踪['y']+=元组([y]) #节点\跟踪['hovertext']+=元组([hovertext]) #节点跟踪['text']+=元组([text]) 索引=索引+1 对于节点,枚举中的邻接(G.adjacency()): 节点跟踪['marker']['color']+=tuple([len(邻接[1])) node_info=邻接[0]#+'('+str(邻接[1])+'))'#+'('+str(len(邻接[1]))+'连接)' 节点跟踪['text']+=元组([node\u info]) traceRecode.append(节点\跟踪) 图={ “数据”:traceRecode, “布局”:go.layout(title='Document Overview',showlegend=False,hovermode='closest', 边距={'b':40,'l':40,'r':40,'t':40}, xaxis={'showgrid':False,'zeroline':False,'showticklabels':False}, yaxis={'showgrid':False,'zeroline':False,'showticklabels':False}, 高度=1000, 单击模式=”事件+选择“, 注释=[ 口述( ax=(G.nodes[edge[0]['pos'][0]+G.nodes[edge[1]['pos'][0])/2, ay=(G.nodes[edge[0]['pos'][1]+G.nodes[edge[1]['pos'][1])/2,axref='x',ayref='y', x=(G.nodes[edge[1]['pos'][0]*3+G.nodes[edge[0]['pos'][0])/4, y=(G.nodes[edge[1]['pos'][1]*3+G.nodes[edge[0]['pos'][1])/4,xref='x',yref='y', showarrow=True, 箭头=4, 箭头大小=2, 箭头宽度=1, 不透明度=1 )对于G.边中的边] )} app.layout=html.Div([ 图(图=图 ), ]) 如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu': app.run_服务器(debug=True)
我从中找到了这个代码

这导致:

然而,错误的方向是错误的。(有关正确的方向,请参见红色箭头。)

我想要实现的是(“Github repo中的Bob”和“Type1”),即在节点上悬停时显示文档名称、描述和ID:

然而,当我注释行时,就像这样

index = 0
for node in G.nodes():
    x, y = G.nodes[node]['pos']
    hovertext = "Document Name: " + str(G.nodes[node]['Doc']) + "<br>" + "Document ID: " + str(G.nodes[node]['DocumentID'])
    text = nodes['Doc'][index]
    node_trace['x'] += tuple([x])
    node_trace['y'] += tuple([y])
    node_trace['hovertext'] += tuple([hovertext])
    node_trace['text'] += tuple([text])
    index = index + 1

# for node, adjacencies in enumerate(G.adjacency()):
#     node_trace['marker']['color']+=tuple([len(adjacencies[1])])
#     node_info = adjacencies[0] #+ ' (' +str(adjacencies[1]) + ')' #+' (' +str(len(adjacencies[1])) + ' connections)'
#     node_trace['text']+=tuple([node_info])
index=0
对于G.nodes()中的节点:
x、 y=G.nodes[node]['pos']
hovertext=“文档名称:”+str(G.nodes[node]['Doc'])+”
“+”文档ID:“+str(G.nodes[node]['DocumentID'])) text=节点['Doc'][索引] 节点跟踪['x']+=元组([x]) 节点跟踪['y']+=元组([y]) 节点\跟踪['hovertext']+=元组([hovertext]) 节点跟踪['text']+=元组([text]) 索引=索引+1 #对于节点,枚举中的邻接(G.adjacency()): #节点跟踪['marker']['color']+=tuple([len(邻接[1])) #node_info=邻接[0]#+'('+str(邻接[1])+'))'#+'('+str(len(邻接[1]))+'连接)' #节点跟踪['text']+=元组([node\u info])
但是,这会导致一个错误:

Traceback (most recent call last):
  File "C:\Users\rothstem\Desktop\LearnDash\StackEX\app.py", line 73, in <module>
    hovertext = "Document Name: " + str(G.nodes[node]['Doc']) + "<br>" + "Document ID: " + str(G.nodes[node]['DocumentID'])
KeyError: 'Doc'
回溯(最近一次呼叫最后一次):
文件“C:\Users\rothstem\Desktop\LearnDash\StackEX\app.py”,第73行,在
hovertext=“文档名称:”+str(G.nodes[node]['Doc'])+”
“+”文档ID:“+str(G.nodes[node]['DocumentID'])) KeyError:“Doc”

我不太明白,因为上面定义了
'Doc'

在图形创建过程中,您创建了节点属性
“Description”

因此,您只需将
“Doc”
替换为
“Description”

hovertext=“文档名称:”+
nx.set_node_attributes(G, nodes.set_index('Doc')['Description'].to_dict(), 'Description')
hovertext = "Document Name: " + str(G.nodes[node]['Description']) + "<br>" + "Document ID: " + str(G.nodes[node]['DocumentID'])