Interactive Visualization with Plotly and Dash
For around 3 years of my experience I was using matplotlib for visualization, around 2 months back following an advice of my colleague, I gave a try to plotly and dash. I was so impressed from the library that I have posted tutorials about these libraries on my YouTube channel “when math’s meets coding”. Today I am going to share my experience with these libraries this may motivate others to give a try to Plotly and Dash.
Check out Complete video Tutorial for Plotly and Dash
Plotly have a clear advantage over matplotlib when it comes to the interactivity, reason is simple it is written in plotly.js which is built in d3.js. editing or modifying plots is as simple as writing a CSS code. Plotly with Dash is a complete capsule solution for visualization in python. with help of plotly and dash you can develop a complete visualization application with a singe page script in python.
Dash is another open source library with inbuilt flask application which permits you host your plots on provided web address or IP.
All the codes and article are available on GitHub. After gaining basic understanding of such library its best practice to solve some problem with help to underlying library. In this article I will try to give basic introduction of plotly and dash components then try to make a simple dashboard.
Idea over here is to create a dashboard with interactive drop-down menu with below steps
- Create a random data-generator with numpy and pandas
- Create layout of dashboard with drop-down menu
- Create a category column in the random data-set with three inbuilt category “good”, “bad” and “worst” now put these category in the drop-down
- Once user select any category from drop-down apply filter for that category in the data-frame and plot filtered data in the dashboard
Lets understand these components with coding
Install dependencies
pip install plotly
pip install dash
Importing all required libraries
import plotly
import dash
import plotly.offline as pyo
import plotly.graph_objs as go
import numpy as np
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import State, Input, Output
import pandas as pd
Random data Generating function
Writing a random data-frame generating function whose data utilized to create dashboards
global cat_g ,sample_type
cat_g = ["good","bad","worst"]
def datagen():
my_sample_data = np.random.random_sample([100,3])
sample_Cat = [cat_g[np.random.randint(0,3)] for i in range(100)]
Base_Data = pd.DataFrame(my_sample_data,columns=["val_1","val_2","val_3"])
Base_Data["sample_Cat"] = sample_Cat
return(Base_Data)
Our Objective to develop a dashboard which will look like this
Dash Core components
Dash core components are drop-down, Slider ,range-slider etc you can put all these component with small script for details about these components visit below page
Values and Labels
You need to create values and label dictionary to use dash core components, label will come on the UI and values will be forwarded to the function which user interact with the dashboard this can be done as below.
cat_g = ["good","bad","worst"]## Creating values and labels for drop-down
options_list = []
for i in cat_g:
options_list.append({'label': i, 'value': i})
Here “good”, “bad” and “worst” will be seen on the dashboard and passed to the figure generating function.
Figure Generator Function
You need to write a function which will generate figure based on given filtered data, here is the sample code for it
def fig_generator(sample_data):
sample_data = sample_data.reset_index(drop=True)
sample_data.head()
plot_data =[]for i in range(1,4):
plot_data.append(go.Scatter(x=sample_data.index, y=sample_data['val_'+ str(i)], name = 'val_'+ str(i) ))
plot_layout = go.Layout(title = " This plot is generated using plotly ")fig = go.Figure( data = plot_data ,layout = plot_layout)return(fig.data,fig.layout)
Dash Html component
For creating a web based application you need html components. Dash provides these html components like Div tags Header. For more information about Dash Html components check out below link
Defining Dash Layout
You need to define a layout for dash in which you can provide styling with css components, do not forget to provide id’s to all html components. Id’s are the reference for these placeholders , For changing anything inside the placeholder you need to create a call back function then by giving the reference id’s.
Callback Function in dash
For any change based on users input given in drop-down you need to create a call back function all input and output components id’s you need to provide as arguments of the callback function here is the call back function used in our code.
@app.callback(Output("plot_area", 'figure'),
[Input("drop_down_1", "value")])
def updateplot(input_cat):
df= datagen()
sample_data = df[df["sample_Cat"] == input_cat ]
trace,layout = fig_generator(sample_data)
return {
'data': trace,
'layout':layout
}
if __name__=='__main__':
app.run_server()
Complete Script
Here is the complete script that can be utilized to generate such dashboard in python.