Black Lives Matter. Please consider donating to Black Girls Code today.
Dash HoloViews is now available! Check out the docs.

Stuck with Callbacks for graph

Hello all,

I have been using Plotly alot and I really like the results. I have been using Jupyter Notebooks in combination with Plotly and I am getting quite the hang in making the graphs and understanding how Plotly works (atleast, I think I am :P). However, I want to plunge in the next step and that is making interactive ‘apps’ (more like reports) for data analysis purposes. I have been succesful with getting my charts I used in my notebooks to work. However I really want to go more interactive and personalise it more for when I am skilled enough to put this in action in the longer term.

So in this case, I am trying to replicate the graph with slider and corresponding callback, however with some dummy data of my own to reduce complexity, as I have a hard time understanding the callbacks used by data which is not my own and quite seemingly complex, the ones in the user manual that is.

For now, i just want to have a slider which loads the graph corresponding to the column ‘Meting’. This column has three unique values, ‘Meting 1’, ‘Meting 2’ and ‘Meting 3’. I want to show the values of column ‘Stroomsnelheid’ belonging to each of the ‘Meting’ in the Y axis, and the time in the X axis.

However, the result is just an empty graph with a disfunctional slider. The full combined graph briefly flashes before the graph is empty. I notice on the X axis, the range turns from -1 to 6 instead of a time taken from the pandas dataframe.

I think my problem here is the only rudimentary knowledge I have right now of Pandas, I have only been scraping the surface of the possibilities… another possibility is the ‘traces’ at line 75 and 79, it does not get referenced somewhere (I think?). However removing it does not work neither. What am I doing wrong and how can I solve this, so I can hopefully have a working callback and expand my knowledge from here?

Link to CSV file: http://s000.tinyupload.com/?file_id=27666644796211953420
Here is the code:

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

app = dash.Dash()

df1 = pd.read_csv(
   'dash/grafiekupdatetest/dummydata.csv', sep=';',)

available_indicators = df1['Meting'].unique()

def generate_table(dataframe, max_rows=50):
    return html.Table(
        # Header
        [html.Tr([html.Th(col) for col in dataframe.columns])] +

        # Body
        [html.Tr([
            html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
        ]) for i in range(min(len(dataframe), max_rows))]
    )

app.layout = html.Div([

dcc.Graph(
    figure=go.Figure(
        data=[
            go.Scatter(
                x=(df1['Tijd']),
                y=(df1['Stroomsnelheid']),
                name='Dummy data',
                marker=go.Marker(
                    color='rgb(55, 83, 109)'
                )
            ),
        ],
        layout=go.Layout(
            title='Stroomsnelheid',
            showlegend=True,
            legend=go.Legend(
                x=0,
                y=1.0
            ),
            margin=go.Margin(l=40, r=0, t=40, b=30)
        )
    ),
    style={'height': 300},
    id='interactieve-grafiek'
),

    dcc.Slider(
        id='meting-nummer',
        min=df1['Meting'].min(),
        max=df1['Meting'].max(),
        value=df1['Meting'].min(),
        step=None,
        marks={str(Meting): str(Meting) for Meting in df1['Meting'].unique()}
    ),

html.Div(children=[
    html.H4(children='Dummy metingen'),
    generate_table(df1)
])

])


@app.callback(
    dash.dependencies.Output('interactieve-grafiek', 'figure'),
    [dash.dependencies.Input('meting-nummer', 'value')])
def update_figure(selected_meting):
    filtered_df = df1[df1.Meting == selected_meting]
    traces = []
    for i in filtered_df.Meting.unique():
        df_by_Meting = filtered_df[filtered_df['Meting'] == i]
append(go.Scatter(
            x=df_by_Meting['Tijd'],
            y=df_by_Meting['Stroomsnelheid'],
            text=df_by_Meting['Stroomsnelheid'],
            mode='lines',
            opacity=0.7,
            name=i
        ))

    return {
        'data': traces,
        'layout': go.Layout(
            xaxis={'type': 'linear', 'title': 'Tijd', 'range': df1['Tijd']},
            yaxis={'title': 'Stroomsnelheid', 'range': [0, 2]},
            margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
            legend={'x': 1, 'y': 1},
            hovermode='closest'
        )
    }

if __name__ == '__main__':
    app.run_server()