Uncover the strengths and weaknesses of Plotly Dash and Streamlit as Python frameworks for app development, tailored to beginners seeking the ideal choice.

In this blog, we will cover the below topics

  • Overview of web development frameworks in Python
  • What is Plotly Dash?
    – A step-by-step guide to learning plotly dash
    – Build a web app with plotly dash
  • What is Streamlit?
    – A step-by-step guide to learning Streamlit
    – Build a web app with Streamlit
  • Comparative study of both the frameworks
  • Conclusion

Introduction:

Python offers a plethora of web development frameworks that cater to different needs and preferences. Two popular frameworks for building interactive web applications in Python are Streamlit and Plotly Dash. In this blog post, we will compare these frameworks, highlighting their key features, use cases, and trade-offs.

One of the ways to express your ideas is to build an app. It’s a beautiful journey from ideation to creation

What is Streamlit?

Streamlit is a powerful Python framework that simplifies the process of creating interactive web applications for data science and machine learning projects. With its intuitive and user-friendly interface, Streamlit enables developers to quickly build and deploy applications without the need for extensive web development experience.

What is Plotly Dash?

Dash is an open-source Python framework used for building analytical web applications and is built on top of Flask, Plotly.js, and React.js. Its simple and easy-to-use framework lets data scientist put their complex model behind the app and the interactive interface enables the users to make business decisions that are backed by data and derived from models.

Guide to learning Streamlit

Streamlit provides a limited set of built-in UI components, including buttons, sliders, and data tables. It integrates seamlessly with popular data science libraries like Pandas, Matplotlib, and plotly, allowing developers to create interactive visualizations with ease. However, Streamlit’s UI capabilities are relatively basic compared to Dash.

Step 1: Install Streamlit
Begin by installing Streamlit using pip or conda. Create a new virtual environment for your project and install the necessary dependencies. Set up your development environment with your preferred code editor or IDE. We will yahoo finance API to fetch data for the stock for a defined period. To build our app, let’s create a Python file by the name Stock_App_Streamlit.py and import the libraries.

import streamlit as st
import pandas as pd
import yfinance as yf
import plotly.graph_objects as go

Step 2: Understand the basics of Streamlit
Familiarize yourself with the key concepts of Streamlit. Learn about the Streamlit script, which consists of Python code that generates the web application. Understand how to use Streamlit’s core components, such as sliders, buttons, and text inputs, to create interactive elements in your application. For our app, let us add a title for the dropdown and set stock names in the sidebar.

# Get a list of stock symbols
stocks = ['AAPL', 'GOOGL', 'MSFT', 'AMZN']

# Add a title for the dropdown
st.sidebar.markdown("<h3>Select a stock</h3>", unsafe_allow_html=True)
selected_stock = st.sidebar.selectbox('', stocks)

Step 3: Build a Streamlit application
Create your first Streamlit application by importing the Streamlit library and writing your code. Start with a basic example, such as displaying a title or an image. Streamlit automatically updates the application whenever you save changes to the script, allowing you to see immediate updates in the browser. Let’s add the title at the top.

# Add a title
st.markdown("<h1 style='text-align: center; color: blue;'>Stock Price Chart</h1>", unsafe_allow_html=True)

Step 4: Add interactivity with Streamlit widgets
Streamlit provides a variety of widgets that allow users to interact with your application. Experiment with different types of widgets, such as sliders, dropdowns, checkboxes, and buttons. Update the content of your application based on user inputs to create dynamic and engaging experiences.

Step 5: Visualize data with Streamlit
Streamlit seamlessly integrates with popular data visualization libraries such as Matplotlib and Plotly. Utilize these libraries to create interactive plots and charts within your Streamlit application. Display data tables, histograms, line charts, or any other visualizations to communicate insights effectively. We will use plotly and create the line chart.

# Create a line chart for the stock's closing prices using Plotly
fig = go.Figure(data=go.Scatter(x=stock_data.index, y=stock_data['Close']))
fig.update_layout(title=f'{selected_stock} Stock Price',
xaxis_title='Date',
yaxis_title='Close Price')
# Display the chart
st.plotly_chart(fig)

Step 6: Deploy your Streamlit application
Streamlit provides an easy way to deploy your application to share it with others. Streamlit Sharing allows you to host your application in the cloud and share the link with colleagues or collaborators. Follow the Streamlit Sharing documentation to deploy your application and make it accessible to others. Please refer to Streamlit Gallery for some inspiration.

Let us bring all the code chunks together and run the app locally on our machine.

import streamlit as st
import pandas as pd
import yfinance as yf
import plotly.graph_objects as go

# Add a title
st.markdown("<h1 style='text-align: center; color: blue;'>
Stock Price Chart</h1>", unsafe_allow_html=True)

# Get a list of stock symbols
stocks = ['AAPL', 'GOOGL', 'MSFT', 'AMZN']

# Add a title for the dropdown
st.sidebar.markdown("<h3>Select a stock</h3>", unsafe_allow_html=True)

# Create a dropdown menu for stock selection
selected_stock = st.sidebar.selectbox('', stocks)

# Retrieve the stock data using Yahoo Finance API
stock_data = yf.download(selected_stock, start='2022-01-01', end='2022-12-31')

# Create a line chart for the stock's closing prices using Plotly
fig = go.Figure(data=go.Scatter(x=stock_data.index, y=stock_data['Close']))
fig.update_layout(title=f'{selected_stock} Stock Price',
xaxis_title='Date',
yaxis_title='Close Price')

# Display the chart
st.plotly_chart(fig)


# Run the application by the terminal
<project folder>streamlit run Stock_App_Streamlit.py
Source: Author

Guide to learning Plotly Dash

Plotly Dash excels in terms of UI components and visualization capabilities. It offers a vast array of interactive components, such as dropdowns, graphs, maps, and more. Dash leverages the power of Plotly.js, a JavaScript library for creating interactive plots, which enables developers to build visually stunning and highly customizable dashboards. With Dash, you can create complex layouts and incorporate advanced visualizations effortlessly.

Step 1: Understand the basics of Plotly and Dash
Before diving into web development with Dash, it’s important to have a good understanding of Plotly, which is a powerful library for creating interactive visualizations in Python. Familiarize yourself with Plotly’s syntax, chart types, and customization options. This knowledge will serve as a foundation for working with Dash. We will yahoo finance API to fetch data for the stock for a defined period. To build our app, let’s create a Python file by the name Stock_App_Dash.py

Step 2: Set up your development environment
To get started with Dash, ensure that you have a Python development environment set up on your machine. Install the necessary dependencies, including the Plotly and Dash libraries. You can use a package manager like pip or conda to install these dependencies.

import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import yfinance as yf
import plotly.graph_objects as go

Step 3: Learn the key concepts of Dash
Dash is a framework that allows you to build interactive web applications using Python. It follows a component-based approach, where you create reusable components and assemble them to build the application. Learn about Dash’s core concepts, such as layout, callbacks, and components like HTML tags, core components, and Plotly components.

Let’s add a title and also configure the dropdown with stock names

html.H1('Stock Price Chart', style={'text-align': 'center', 'color': 'blue'}),
dcc.Dropdown(
id='stock-dropdown',
options=[
{'label': 'AAPL', 'value': 'AAPL'},
{'label': 'GOOGL', 'value': 'GOOGL'},
{'label': 'MSFT', 'value': 'MSFT'},
{'label': 'AMZN', 'value': 'AMZN'}
],
value='AAPL'
)

Step 4: Create your first Dash application
Start by creating a simple Dash application to understand the basic structure. Import the necessary modules, define the layout of your application using HTML and Dash components, and run the application. For example, you can create a simple application that displays a line chart using Plotly something we will do with the app we are building.

Step 5: Add interactivity with callbacks
One of the powerful features of Dash is the ability to add interactivity through callbacks. Callbacks allow you to update the content or behavior of your application based on user interactions. Learn how to define callbacks, specify input and output components, and write the corresponding callback functions. For example, you can create a callback that updates a line chart based on user-selected options. We will implement this in our app.

# Define the callback function to update the chart
@app.callback(
dash.dependencies.Output('stock-chart', 'figure'),
[dash.dependencies.Input('stock-dropdown', 'value')]
)
def update_chart(selected_stock):
# Retrieve the stock data using Yahoo Finance API
stock_data = yf.download(selected_stock, start='2022-01-01', end='2022-12-31')

# Create a line chart for the stock's closing prices using Plotly
fig = go.Figure(data=go.Scatter(x=stock_data.index, y=stock_data['Close']))
fig.update_layout(title=f'{selected_stock} Stock Price', xaxis_title='Date', yaxis_title='Close Price')

return fig

Step 6: Explore Dash extensions and advanced features
Dash offers various extensions and advanced features that can enhance your web application. Explore features like Dash Bootstrap Components for styling, Dash DataTable for interactive tables, and Dash Authentication for secure user authentication. Additionally, you can integrate other Python libraries, such as Pandas, to handle data manipulation and preprocessing within your Dash application.

Step 7: Build complex Dash applications
Once you have a good understanding of the basics, challenge yourself by building more complex Dash applications. Explore real-world use cases and leverage the full capabilities of Dash to create interactive data dashboards, machine learning model visualizations, or any other custom web application that suits your needs. You can explore Dash Gallery for some inspiration.

Let us bring all the code chunks together and run the app locally on our machine.

import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import yfinance as yf
import plotly.graph_objects as go

# Create the Dash app
app = dash.Dash(__name__)

# Add a title and define the dropdown
app.layout = html.Div([
html.H1('Stock Price Chart', style={'text-align': 'center', 'color': 'blue'}),
html.Div([
html.H3('Select a stock'),
dcc.Dropdown(
id='stock-dropdown',
options=[
{'label': 'AAPL', 'value': 'AAPL'},
{'label': 'GOOGL', 'value': 'GOOGL'},
{'label': 'MSFT', 'value': 'MSFT'},
{'label': 'AMZN', 'value': 'AMZN'}
],
value='AAPL'
)
], style={'width': '30%', 'display': 'inline-block', 'vertical-align': 'top'}),
dcc.Graph(id='stock-chart')
])

# Define the callback function to update the chart
@app.callback(
dash.dependencies.Output('stock-chart', 'figure'),
[dash.dependencies.Input('stock-dropdown', 'value')]
)
def update_chart(selected_stock):
# Retrieve the stock data using Yahoo Finance API
stock_data = yf.download(selected_stock, start='2022-01-01', end='2022-12-31')

# Create a line chart for the stock's closing prices using Plotly
fig = go.Figure(data=go.Scatter(x=stock_data.index, y=stock_data['Close']))
fig.update_layout(title=f'{selected_stock} Stock Price', xaxis_title='Date', yaxis_title='Close Price')

return fig

# Run the app
if __name__ == '__main__':
app.run_server(debug=True)

# Run the application by the terminal and navigate to
# http://localhost:8050 in the browser to view the app
<project folder>python Stock_App_Dash.py
Source: Author

Comparative study

Now, that we successfully built our apps with the same dataset and a more or less similar layout, it is important to note these frameworks appear similar for simple use cases but have distinctly different features. Here is a cheat sheet for quick reference.

Conclusion

Both Streamlit and Plotly Dash are powerful Python web development frameworks that offer distinct advantages. Streamlit’s simplicity and rapid development capabilities make it an excellent choice for data-focused applications and prototypes. On the other hand, Plotly Dash provides a more comprehensive set of features, including advanced visualizations and flexible UI components, making it ideal for building complex dashboards and scalable applications.

Ultimately, the choice between Streamlit and Plotly Dash depends on your specific project requirements and skillset. If you value simplicity and quick prototyping, Streamlit is a fantastic option. For more control, customization, and advanced visualizations, Plotly Dash offers a powerful framework to bring your web application to life.

I hope you liked the article and found it helpful.

You can connect with me — on Linkedin and Github

References:

Plotly Python Graphing Library Documentation: https://plotly.com/python/
Dash User Guide: https://dash.plotly.com/
Dash DataTable: https://dash.plotly.com/datatable

Streamlit Documentation: https://docs.streamlit.io/
Streamlit Gallery: https://streamlit.io/gallery

6 Comments

  1. Awesome website you have here but I was wondering
    if you knew of any user discussion forums that cover the
    same topics discussed here? I’d really like to be a part of
    online community where I can get feed-back from other knowledgeable people that share
    the same interest. If you have any suggestions,
    please let me know. Many thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *