Отображение атрибутов в Dash / Plotly приводит к KeyError - PullRequest
2 голосов
/ 09 июля 2020

Я пытаюсь визуализировать ссылки из документов. Для этого у меня есть 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 Laboratory, что указывает на Windows PC manual, et c.

Код, который я использую для визуализации этой сети, работает с 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)

Я нашел этот код здесь Репозиторий Github .

Это приводит к: Неправильным стрелкам

Однако направление ошибки неверное. (См. Красную стрелку для правильного направления.)

Я хочу достичь этого («Боб» и «Тип1» из репозитория Github), т.е. отображать имя документа, описание и идентификатор при наведении курсора на узел: goalAttributes

Однако, когда я комментирую строки, например,

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])

Однако это приводит к ошибке:

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'

, что я не совсем понимаю, поскольку 'Doc' определено выше.

1 Ответ

0 голосов
/ 09 июля 2020

Во время создания графа вы создали атрибут узла "Description":

nx.set_node_attributes(G, nodes.set_index('Doc')['Description'].to_dict(), 'Description')

Поэтому вам просто нужно заменить "Doc" на "Description":

hovertext = "Document Name: " + str(G.nodes[node]['Description']) + "<br>" + "Document ID: " + str(G.nodes[node]['DocumentID'])
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...