Обратный вызов приложения не обновляет график, если используется условие - PullRequest
0 голосов
/ 08 июля 2019

Я загружаю свои данные в приложение Dash и создаю радиоэлемент, чтобы выбрать, какой график я хочу создать из него. На данный момент я создал только одну графовую функцию, хранящуюся в отдельном файле graph_definitions.py:

def lineplot(dat, testmode=False):
    '''
    testmode: If testomde is set to True only the first 10 items will be used in the graph
    '''     
    print('graph is called')
    cells=list(dat['unique_id'].unique())

    if testmode==True:

        cells=cells[0:10]



    #initiating traces as a list
    traces=[]
    #getting trace IDs from unique IDs (cells)

    #looping through the cells
    for c in cells:   
        print('data looping')
        #appending x, y data based on current cell to the list of traces
        traces.append(go.Scatter(
        x=dat.loc[dat['unique_id']==c]['Location_Center_X_Zeroed'],        
        y=dat.loc[dat['unique_id']==c]['Location_Center_Y_Zeroed']
        )
    )

    print('looping finished')
    return {'data' :traces}

Остальную часть кода смотрите ниже. Теперь проблема заключается в следующем: Обратный вызов приложения работает, все распечатки из функции графика созданы и кажутся правильными, но график не обновляется. Когда я, однако, опускаю условие if, чтобы получить

def get_value(value):
    print(value)
    print(type(value))
    print(GD.lineplot(df, testmode=True))
    return GD.lineplot(df, testmode=True)

Ему действительно удается обновить график, как только я выбираю значение в радиоэлементах. Теперь я не хочу иметь только один вариант графика, но хотел бы создать несколько графиков и выбирать между ними, так что это не очень полезно. Кто-нибудь может объяснить мне, почему условия создают проблему?

import base64
import datetime
import io

import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import dash_table

import pandas as pd
import sys
import os


sys.path.append(os.path.realpath(__file__))
import graph_definitions as GD


external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
#%% app upload
global df
df=[]
app.layout = html.Div([

    dcc.Upload(
        id='upload-data',
        children=html.Div([
            'Drag and Drop or ',
            html.A('Select Files')
        ]),
        style={
            'width': '100%',
            'height': '60px',
            'lineHeight': '60px',
            'borderWidth': '1px',
            'borderStyle': 'dashed',
            'borderRadius': '5px',
            'textAlign': 'center',
            'margin': '10px'
        },
        # Allow multiple files to be uploaded
        multiple=True
    ),
    html.Table(id='output-data-upload'),
    dcc.RadioItems(
    options=[
        {'label': 'lineplot', 'value': 'lineplot'},
        {'label': 'None', 'value' : 'None'}

    ],
    value='None',
    id='graph_selector'),
    dcc.Graph(id='migration_data')
])

#%%layouts
def generate_table(df):
    return dash_table.DataTable(
                data=df.to_dict('records'),
                columns=[{'name': i, 'id': i} for i in df.columns],
                fixed_rows={'headers':True, 'data':0},
                style_cell={'width' :'150px'}
            )


#%%
#backup
def parse_contents(contents, filename, date):
    content_type, content_string = contents.split(',')

    decoded = base64.b64decode(content_string)
    try:
        global df
        if 'csv' in filename:
            # Assume that the user uploaded a CSV file
            df = pd.read_csv(
                io.StringIO(decoded.decode('utf-8')))
        elif 'xls' in filename:
            # Assume that the user uploaded an excel file
            df = pd.read_excel(io.BytesIO(decoded))

    except Exception as e:
        print(e)
        return html.Div([
            'There was an error processing this file.'
        ])
    #selection of graphs
    return html.Div([
        html.H5(filename),
        html.H6(datetime.datetime.fromtimestamp(date)),

        generate_table(df),
        html.Hr(),  # horizontal line

        # For debugging, display the raw contents provided by the web browser
        html.Div('Raw Content'),
        html.Pre(contents[0:200] + '...', style={
            'whiteSpace': 'pre-wrap',
            'wordBreak': 'break-all'
        })
    ])

#%% update after upload
@app.callback(Output('output-data-upload', 'children'),
              [Input('upload-data', 'contents')],
              [State('upload-data', 'filename'),
               State('upload-data', 'last_modified')])
def update_output(list_of_contents, list_of_names, list_of_dates):
    if list_of_contents is not None:
        children = [
            parse_contents(c, n, d) for c, n, d in
            zip(list_of_contents, list_of_names, list_of_dates)]
        return children
@app.callback(Output('migration_data', 'figure'),
              [Input('graph_selector', 'value')])
def get_value(value):
     print(value)
     if 'df' in globals():
       if value=='lineplot':
             print(GD.lineplot(df, testmode=True))
             return GD.lineplot(df, testmode=True)

редактирование: Я мог бы обойти эту проблему, сохранив функцию в словаре и вызвав ее по ключу.

graph_options={'lineplot':GD.lineplot}
def get_value(value):
    return graph_options[value](df, testmode=True)

В случае, если я не могу использовать условное выражение, это, однако, будет работать, только если входные данные для всех графиков одинаковы.

...