Python For Data Science — Advanced Guide to Plotly Dash Interactive Visualizations | by Nicholas Leong | Towards Data Science

Greetings data practitioners,I assume you are aware of the increase in demand for people who know how to communicate data. This is exactly why we should always seek to improve, learn more, and sharpen our skills in the data science industry.
Even with all the hype around Machine Learning, Data Visualizations do not lose their importance. Exploratory Data Analysis is often required before any Machine Learning is even planned out.
Large tech companies often need to communicate the data they own. We are the ones that execute.
A very good example would be google and their known, google trends.
Hence, building clean and beautiful visualizations is a valuable skill that will definitely make you stand out from the crowd.
Have you heard of Dash by Plotly?
Dash is the new kid on the block. I wrote about it here.
towardsdatascience.com
Basically, Dash is the new Python library that allows you to build amazing data visualization apps with highly customization user interface without the need to know any HTML, CSS, or Javascript.
It takes away the headaches of deploying apps, making it mobile responsive and easily maintainable.
But you know that already, what was I thinking.
You’re not here for that, you want to know more.
In this article, we will talk about how you can add more customizations to your Dash web app. We will also go in-depth on how you can update the dashboard without any interactions, in real-time.
Dash visualizations are based on Plotly.It’s important that you understand the fundamentals of building simple Plotly Graphs. I wrote about building the basic Plotly graphs here, covering the concepts you need to understand while building any sort of graph.
towardsdatascience.com
In order to work with Plotly, you will need to perform some soft transformations on your data with Pandas.
I got you covered. I happen to have written A Guide to Pandas as well.If you need to refresh your memory on Pandas, please go through it.
towardsdatascience.com
pip install dash
Working with Jupyter Notebooks...
import dashimport dash_core_components as dccimport dash_html_components as htmlimport plotly.graph_objs as goimport pandas as pdfrom dash.dependencies import Input, Output
In this section, we will be talking about making your dashboard live.
Yes, you heard it right.
Dash allows its users to automate dashboards in real-time by updating its data source, without any interactions whatsoever. This is achieved by implementing the interval component.
The interval component from dash core components is a trigger that will fire callbacks periodically. To implement this on the app, simply connect the interval to a tag or graph you need to update, and let the magic happen.
We will explore this with a simple example.
app = dash.Dash()app.layout = html.Div([    html.H1(id='live-counter'),    dcc.Interval(        id='1-second-interval',        interval=1000,         n_intervals=0    )])@app.callback(Output('live-counter', 'children'),              [Input('1-second-interval', 'n_intervals')])def update_layout(n):    return 'This app has updated itself for {} times, every second.'.format(n)if __name__ == '__main__':    app.run_server()
In this section, we have simply defined an H1 tag and an interval component.We then defined a callback function, taking the interval component as an input and the H1 tag as the output.
An important property in the component is the interval property, which defines how often the component will trigger. Here, we are taking 1-second intervals.
What this means is that the callback function will trigger every 1 second automatically.
Lastly, we can make use of the n property in the interval component which updates itself according to the time interval we have defined. Simply insert n as part of the text we displayed to show the real-time changes.
Let’s bring it up a notch, shall we?How do we implement this for an actual graph?
Simple, we update the graph itself.
In this block of code, we are simply defining a graph component and an interval component. We then defined a callback function, taking the interval component as an input and the graph’s figure as the output.
Before I jump into the explanation, a good flow chart always helps.
For every second, new data with a random number is appended into our data source. A new graph is then plotted based on that updated data source. The graph on the app is then replaced with the updated graph.
Here, we have simply inserted random numbers as data into our data source. However, if you are following, you will know that you can easily append/overwrite your data source based on your pipeline.
Are you web-scraping data in real-time?
Are you visualizing transactional data for your website?
You can easily declare that as your data source and visualize it every second/minute/day.
I hope you realize by now how powerful Dash is. It is only up to your imagination on how you can take advantage of it.
Note: Be mindful of updating graphs in too small of an interval. It is not wise to have real-time data without having a real use case for it because there might be extremely heavy computations in updating data sources, not to mention plotting extremely heavy graphs.
So you’re able to build graphs and automate them by now. What’s next?
You need to design and customize your web app so it looks beautiful to the user. From color to positioning, Dash allows you to do so easily with a line of code.
CSS stands for Cascading Style Sheets which is the main language to style your HTML tags. If you wish to beautify your web app, learning CSS is a must.
Dash allows you to add CSS in the Python code itself.For nearly every component in Dash, there is a property named ‘style’ which allows you to declare the CSS for that component through a Python Dictionary.
html.H1(children='Hello World!',style={'width':'20%','display':'inline-block'})
That’s cool and all. However, there is a better way to declare your CSS if your web app scales.
Exclusively declaring CSS for each component is inefficient, it will also slow down the load time for the app.
Hence, we can use the Classname solution in Dash, which is essentially the class attribute for your HTML element.
In the same folder where you started your Dash code, create another folder named assets and place all your CSS and Javascript code in it. By default, the latest Dash version will read everything that ends with .css and .js from the assets folder and apply it to the web app.
app.py:
app = dash.Dash(__name__)app.layout = html.H1(children='Hello World!', className= 'H1-Text H1-Text-Display')if __name__ == '__main__':    app.run_server()
app.css:
.H1-Text{ width:20%;}.H1-Text-Display{ display:inline-block;}
This way, you can reuse classes for different components in your Dash code. It makes it cleaner and faster.
Note: In order for Dash to read the assets folder by default, kindly include __name__ in while declaring app = dash.Dash(__name__).
Congratulations,you’ve taken yourself to the next level in Dash.
In this article, you’ve learned —
Dash — Real-Time UpdatesDash — Adding CSS
Dash — Real-Time Updates
Dash — Adding CSS
The limit is the sky. Now go, build something, and share it with me. I’m waiting.
We are not done yet with our data journey. I am working on more stories, writings, and guides on the data industry. You can absolutely expect more posts like this. In the meantime, feel free to check out my other articles to temporarily fill your hunger for data.
As usual, I end with a quote.
Data is the new science. Big Data holds the answers. — Pat Gelsinger, CEO of VMware
You can also support me by signing up for a medium membership through my link. You will be able to read an unlimited amount of stories from me and other incredible writers!
I am working on more stories, writings, and guides in the data industry. You can absolutely expect more posts like this. In the meantime, feel free to check out my other articles to temporarily fill your hunger for data.
Thanks for reading! If you want to get in touch with me, feel free to reach me at nickmydata@gmail.com or my LinkedIn Profile. You can also view the code for previous write-ups in my Github.