We use cookies to enhance your experience on the site
CodeWorlds

Streamlit - Interactive Dashboards

Streamlit lets you create interactive web applications for presenting data in Python!

Installation

1pip install streamlit

Basic Application

1# app.py
2import streamlit as st
3import pandas as pd
4import numpy as np
5import matplotlib.pyplot as plt
6
7st.title('🦁 Safari Dashboard')
8st.write('Interactive Safari data analysis')
9
10# Data
11data = pd.DataFrame({
12    'species': ['Lion', 'Elephant', 'Cheetah', 'Giraffe', 'Zebra'],
13    'population': [120, 450, 85, 200, 380],
14    'endangered': [True, False, True, False, False]
15})
16
17st.dataframe(data)

Running

1streamlit run app.py

Interactive Widgets

1import streamlit as st
2
3# Sidebar
4st.sidebar.title('Filters')
5
6# Selectbox
7species = st.sidebar.selectbox(
8    'Select species:',
9    ['All', 'Lion', 'Elephant', 'Cheetah']
10)
11
12# Multiselect
13habitats = st.sidebar.multiselect(
14    'Select habitats:',
15    ['Savanna', 'Forest', 'Desert'],
16    default=['Savanna']
17)
18
19# Slider
20min_population = st.sidebar.slider(
21    'Minimum population:',
22    min_value=0,
23    max_value=1000,
24    value=100
25)
26
27# Number input
28year = st.sidebar.number_input('Year:', 2020, 2024, 2023)
29
30# Checkbox
31show_endangered = st.sidebar.checkbox('Endangered only', value=False)
32
33# Radio buttons
34chart_type = st.sidebar.radio(
35    'Chart type:',
36    ['Bar', 'Pie', 'Line']
37)
38
39# Button
40if st.sidebar.button('Refresh data'):
41    st.experimental_rerun()

Charts in Streamlit

1import streamlit as st
2import pandas as pd
3import matplotlib.pyplot as plt
4import plotly.express as px
5
6# Matplotlib
7fig, ax = plt.subplots()
8ax.bar(data['species'], data['population'])
9st.pyplot(fig)
10
11# Plotly (interactive)
12fig = px.bar(data, x='species', y='population', color='endangered',
13             title='Safari Species Populations')
14st.plotly_chart(fig)
15
16# Built-in Streamlit charts
17st.line_chart(data.set_index('species')['population'])
18st.bar_chart(data.set_index('species')['population'])

Layout and Organization

1import streamlit as st
2
3# Columns
4col1, col2, col3 = st.columns(3)
5
6with col1:
7    st.metric('Species', 150, delta=5)
8
9with col2:
10    st.metric('Population', '12,500', delta=-200)
11
12with col3:
13    st.metric('Endangered', 23, delta=2, delta_color='inverse')
14
15# Tabs
16tab1, tab2, tab3 = st.tabs(['📊 Data', '📈 Charts', '🔍 Analysis'])
17
18with tab1:
19    st.write('Data goes here')
20
21with tab2:
22    st.write('Charts go here')
23
24with tab3:
25    st.write('Analysis goes here')
26
27# Expander
28with st.expander('Show details'):
29    st.write('Detailed information...')
30
31# Container
32with st.container():
33    st.write('Content in a container')

Cache for Performance

1import streamlit as st
2import pandas as pd
3
4@st.cache_data
5def load_data():
6    """Cached data loading."""
7    df = pd.read_csv('large_safari_data.csv')
8    return df
9
10# Data is loaded once and cached
11data = load_data()
12st.dataframe(data)

Complete Application

1# safari_dashboard.py
2import streamlit as st
3import pandas as pd
4import plotly.express as px
5
6st.set_page_config(page_title='Safari Dashboard', page_icon='🦁', layout='wide')
7
8st.title('🦁 Safari Species Dashboard')
9
10# Sidebar filters
11st.sidebar.header('Filters')
12min_pop = st.sidebar.slider('Min population', 0, 500, 50)
13
14# Load data
15@st.cache_data
16def load_data():
17    return pd.DataFrame({
18        'species': ['Lion', 'Elephant', 'Cheetah', 'Giraffe', 'Zebra'] * 3,
19        'population': [120, 450, 85, 200, 380, 130, 460, 80, 210, 390, 125, 455, 82, 205, 385],
20        'year': [2021]*5 + [2022]*5 + [2023]*5,
21        'habitat': ['Savanna', 'Forest', 'Savanna', 'Savanna', 'Savanna'] * 3
22    })
23
24data = load_data()
25filtered = data[data['population'] >= min_pop]
26
27# Metrics
28col1, col2, col3 = st.columns(3)
29col1.metric('Species', filtered['species'].nunique())
30col2.metric('Total Population', filtered['population'].sum())
31col3.metric('Average Population', f"{filtered['population'].mean():.0f}")
32
33# Charts
34col1, col2 = st.columns(2)
35
36with col1:
37    fig = px.bar(filtered, x='species', y='population', color='year',
38                 title='Populations by Species')
39    st.plotly_chart(fig, use_container_width=True)
40
41with col2:
42    fig = px.pie(filtered, values='population', names='species',
43                 title='Population Share')
44    st.plotly_chart(fig, use_container_width=True)
45
46# Data table
47st.subheader('Data')
48st.dataframe(filtered, use_container_width=True)
Go to CodeWorlds