Categories We Write About

Create personalized dashboards with Streamlit

In today’s data-driven landscape, personalized dashboards offer a streamlined way to visualize and interact with data that matters most to individual users. With Python’s Streamlit framework, developers and data enthusiasts can create interactive, real-time, and fully customized dashboards with minimal coding effort. Streamlit allows the rapid development of powerful applications while maintaining a clean and simple code structure.

Understanding Streamlit and Its Advantages

Streamlit is an open-source Python library that turns data scripts into shareable web applications. Unlike traditional dashboarding tools that require knowledge of front-end frameworks or complex deployment procedures, Streamlit simplifies the process with a “write Python, run app” approach. It supports direct integration with popular data science tools like Pandas, NumPy, Plotly, and Matplotlib, which makes it a favorite among data scientists.

Key advantages include:

  • Speed of development: Build a dashboard in minutes with a few lines of code.

  • Interactivity: Add widgets like sliders, dropdowns, and text inputs without needing JavaScript.

  • Real-time updates: Dashboards update as underlying data changes.

  • Customizability: Every component can be tailored for personalized user experience.

Setting Up Streamlit

Before building your dashboard, ensure Streamlit is installed in your environment:

bash
pip install streamlit

Create a Python script (e.g., app.py), which will serve as the entry point for your dashboard. Launch it using:

bash
streamlit run app.py

This command starts a local development server and opens your dashboard in a browser.

Structuring a Personalized Dashboard

A personalized dashboard needs to respond dynamically to individual users’ preferences, roles, or data profiles. Here’s a breakdown of how to implement such features:

1. User Authentication (Basic Personalization)

While Streamlit doesn’t include native user authentication, integration with packages like streamlit-authenticator enables basic login functionality. This is a key step toward delivering a personalized experience.

Example:

python
import streamlit as st import streamlit_authenticator as stauth names = ['Alice', 'Bob'] usernames = ['alice', 'bob'] passwords = ['123', '456'] hashed_passwords = stauth.Hasher(passwords).generate() authenticator = stauth.Authenticate(names, usernames, hashed_passwords, 'dashboard', 'abcdef', cookie_expiry_days=30) name, authentication_status, username = authenticator.login('Login', 'main') if authentication_status: st.write(f'Welcome *{name}*') elif authentication_status == False: st.error('Username/password is incorrect')

2. Loading User-Specific Data

Once authentication is complete, load and display data tailored to the user. Assume a use case where each user has their own CSV data file.

python
import pandas as pd data_files = { 'alice': 'data_alice.csv', 'bob': 'data_bob.csv' } if authentication_status: df = pd.read_csv(data_files[username]) st.dataframe(df)

3. Customizing Dashboard Widgets and Layouts

Personalization goes beyond just showing different datasets. You can render different widgets or views depending on the user profile.

python
if username == 'alice': st.sidebar.title("Alice's Controls") filter_value = st.sidebar.slider('Filter sales above', 0, 1000, 500) st.dataframe(df[df['sales'] > filter_value]) elif username == 'bob': st.sidebar.title("Bob's Preferences") selected_region = st.sidebar.selectbox('Region', df['region'].unique()) st.dataframe(df[df['region'] == selected_region])

4. Dynamic Visualizations

Streamlit supports several visualization libraries. Here’s how to create a personalized chart using Plotly:

python
import plotly.express as px if authentication_status: st.subheader('Sales Analysis') fig = px.bar(df, x='product', y='sales', color='region') st.plotly_chart(fig)

You can enhance personalization by saving user preferences (e.g., chart types, filters) in session state or a backend database.

5. Session State for Custom Interactions

Streamlit’s session state allows you to persist user choices during a session, enabling a more dynamic and personalized interaction.

python
if 'preferred_chart' not in st.session_state: st.session_state['preferred_chart'] = 'Bar' chart_type = st.selectbox('Choose chart type', ['Bar', 'Line', 'Pie']) st.session_state['preferred_chart'] = chart_type if chart_type == 'Bar': st.bar_chart(df.set_index('product')['sales']) elif chart_type == 'Line': st.line_chart(df.set_index('product')['sales'])

Best Practices for Building Personalized Dashboards

  1. Keep it simple: Focus on delivering high-impact visualizations and avoid cluttering the interface.

  2. Use layout containers: Organize content with st.columns() and st.container() for better UX.

  3. Optimize performance: Use @st.cache_data or @st.cache_resource decorators to speed up data loading.

  4. Mobile responsiveness: While Streamlit isn’t fully responsive, designing with vertical stacks and collapsible sections improves mobile usability.

  5. Secure deployment: If deploying on the cloud (e.g., Streamlit Community Cloud or AWS), ensure SSL encryption and strong authentication.

Deployment Options

Streamlit apps can be hosted using several options:

  • Streamlit Community Cloud: Ideal for small apps with authentication layers.

  • Heroku: Offers flexible deployment but may require a bit more setup.

  • AWS, GCP, or Azure: Best for scalable and secure enterprise-level apps.

  • Docker: Containerize your Streamlit app for consistency across environments.

Basic Dockerfile for a Streamlit app:

dockerfile
FROM python:3.9 WORKDIR /app COPY . /app RUN pip install -r requirements.txt EXPOSE 8501 CMD ["streamlit", "run", "app.py", "--server.port=8501", "--server.enableCORS=false"]

Personalization Beyond the Basics

To take dashboard personalization even further:

  • Integrate with databases: Pull user data dynamically from PostgreSQL, MySQL, or MongoDB.

  • Use feature flags: Show/hide features based on user role.

  • Track user behavior: Log user activity to provide recommendations or usage insights.

  • Allow user configuration: Let users build their own dashboards using drag-and-drop widgets (can be built with Streamlit + external JS integrations).

Final Thoughts

Streamlit empowers developers to create customized, user-specific dashboards quickly and effectively. With its intuitive syntax and deep integration with the Python data ecosystem, it is an excellent choice for both simple prototypes and production-grade applications. By layering user authentication, dynamic data loading, and tailored interactivity, developers can build highly personalized dashboards that cater to individual users, teams, or entire organizations.

Share This Page:

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Comments

Leave a Reply

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

Categories We Write About