Another Stage Of Visualization: Be Reactive with Dash
By: Jiwon Jeong
Tags: Data Science, Dash, Visualization, Plotly, Python

Simple scatter plot on a dashboard

I won’t cover the details on Plotly itself, but you can find a nice tutorial for Plotly from this video if it’s necessary. You can also learn how to make a 3D plot or Choropleth Map in the series of the video. Here we’ll make a line plot which shows fluctuations in the stock price.

# Step 3. Create a plotly figure

trace_1 = go.Scatter(x = st.Date, y = st['AAPL.High'],

name = 'AAPL HIGH',

line = dict(width = 2,

color = 'rgb(229, 151, 50)')) layout = go.Layout(title = 'Time Series Plot',

hovermode = 'closest') fig = go.Figure(data = [trace_1], layout = layout)

Now, it’s time for dash-html-components to come into play. We first put a division and then bring the graph inside it. id is giving a name to this component so that we can call it by its name. You’ll understand what this is for later. And then we make a server to run in step 6. If we set the debug mode equals true, we can easily change and update the app while the server is running.

# Step 4. Create a Dash layout

app.layout = html.Div([

dcc.Graph(id = 'plot', figure = fig)

]) # Step 6. Add the server clause

if __name__ == '__main__':

app.run_server(debug = True)

Let’s save this script with the name of app.py and import it on the terminal (or anaconda prompt). Note that the working directory should be the same with where you saved the file.

C:\Users\jjone\Dash> python app.py

If there is no typo or syntax error, you’ll see the localhost address. You can copy and paste it or you can just type localhost:8050 on a new web tab.

Adding a header and a paragraph

We can also have additional components such as putting text data just like HTML. You can find what kind of elements are available here. Let’s put a simple heading and a paragraph on our page.

# Step 4. Create a Dash layout

app.layout = html.Div([

# adding a header and a paragraph

html.Div([

html.H1("This is my first dashboard"),

html.P("Learning Dash is so interesting!!")

],

style = {'padding' : '50px' ,

'backgroundColor' : '#3aaab2'}), # adding a plot

dcc.Graph(id = 'plot', figure = fig)

])

On top of the graph, I’m going to put one more division and add a header and a paragraph inside it. We have two major components, html.Div and dcc.Graph. Inside html.Div , there are two additional components, header ( html.H1 ) and a paragraph ( html.P ). We can change the margin of the components or the background color with the style attribute. It should be designated in a dictionary format supporting CSS properties.

Please pay extra care where the parenthesis starts and ends. It’s important to understand the range of the paragraph for each component. As there are so many parenthesizes and square brackets, it can be confusing at first. And It’s so easy to make a syntax mistake as well.

Put this code at step 4 in our template and see the result. We can simply check the outcome by pressing F5 if the server isn’t shut down.

Now I hope you get the idea of what the dash components and the HTML components are. How to put multiple components and how they go along with together.

Dropdown

Let’s try making a dropdown on our dashboard this time. We’re going to make another plot which changes its y-axis according to the given option. By the documentation of dash components, we can put Dropdown as follows.

As you can see, the options should be in the format of a dictionary. In our case, the options will be the columns only with the continuous variables, from the 2nd column to the 10th. With the list comprehension, we can make the option dictionary in just one line.

features = st.columns[1:-1]

opts = [{'label' : i, 'value' : i} for i in features]

Now instead of the HTML components, we’re going to put the dropdown component at the bottom of the plot. Take a look at the bold font first because others are just for decorating the major two applications. value is the default value of the dropdown.

# Step 4. Create a Dash layout

app.layout = html.Div([

# adding a plot

dcc.Graph(id = 'plot', figure = fig), # dropdown

html.P([

html.Label("Choose a feature"),

dcc.Dropdown(id = 'opt',

options = opts,

value = opts[0])

], style = {'width': '400px',

'fontSize' : '20px',

'padding-left' : '100px',

'display': 'inline-block'})

])

And just as what we did before, we can replace this code at step 4 in our template and check the outcome.

Connecting to graph with callback

To update the graph according to the choice of the dropdown, we need to make a connection between input data (the dropdown) and output data (the graph). This will be done by adding a callback function in step 5.

# Step 5. Add callback functions

@app.callback(Output('plot', 'figure'),

[Input('opt', 'value')]) Output('plot', 'figure'),[Input('opt', 'value')]

Do you remember what id we gave to each component? plot and opt. Therefore we can call them with their name as shown above. We take the input data from the options by the name of opt and give the output to the line plot by the name of plot.

def update_figure(X):

trace_2 = go.Scatter(x = st.Date, y = st[X],

name = X,

line = dict(width = 2,

color = 'rgb(106, 181, 135)'))

fig = go.Figure(data = [trace_1, trace_2], layout = layout)

return fig

So we take the input data and then return the output as we want by creating an update function. What is our input data here? It’s the name of the feature variable selected from the dropdown, and we are to make it as the y-axis of our second line plot. As there is nothing to be changed with the trace_1 , we can simply add trace_2 to the data list. Now if we put this code at step 5 and rerun app.py, the result will be is shown below.

I’d like to briefly talk about a callback before we move on to the next section. Because it’s one of the most frequently used functions while programming any kind of applications. In a nutshell, a callback is a function that is executed later when it gets the real execution command and it’s usually for the purpose of updating. Callback functions don’t work right after they get the command. These people are kind of lazy. They will do their work after the other command lines are executed and we call them back again with the real execution command.

See how our update_figure() works. This function does his work not right after we import this app but when we give the actual input signal to it by “calling back.” This is what a callback function is. It’s totally fine you use this without understanding but I hope you get the rough idea here. You can also find more details from this article.

RangeSlider

Lastly, let’s try a range slider. We’ll add a year range slider to the plot, and it’s very similar to dropdowns. Let’s check the documentation of dash components first.