Streamlit / app.py
AntDX316
Add application file
be783de
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import random
from datetime import datetime
# Set page configuration
st.set_page_config(
page_title="Quick Streamlit Demo",
page_icon="πŸ“Š",
layout="wide",
initial_sidebar_state="expanded"
)
# Add custom CSS
st.markdown("""
<style>
.main-header {
font-size: 2.5rem;
color: #1E88E5;
}
.sub-header {
font-size: 1.5rem;
color: #424242;
}
</style>
""", unsafe_allow_html=True)
# App title
st.markdown('<p class="main-header">Interactive Streamlit Dashboard</p>', unsafe_allow_html=True)
st.markdown("This is a quick demo of Streamlit's capabilities.")
# Sidebar
st.sidebar.title("Controls")
data_size = st.sidebar.slider("Data Points", 10, 500, 100)
chart_height = st.sidebar.slider("Chart Height", 300, 800, 400)
# Define color themes dictionary mapping to actual Plotly color sequences
color_themes = {
"blues": px.colors.sequential.Blues,
"reds": px.colors.sequential.Reds,
"greens": px.colors.sequential.Greens,
"purples": px.colors.sequential.Purples,
"oranges": px.colors.sequential.Oranges
}
color_theme = st.sidebar.selectbox("Color Theme", list(color_themes.keys()))
# Generate random data
@st.cache_data
def generate_data(n_points):
np.random.seed(42)
dates = pd.date_range(start=datetime.now().date(), periods=n_points)
df = pd.DataFrame({
'date': dates,
'value': np.random.randn(n_points).cumsum(),
'category': np.random.choice(['A', 'B', 'C', 'D'], n_points),
'size': np.random.randint(10, 100, n_points)
})
return df
# Create tabs
tab1, tab2, tab3 = st.tabs(["Chart", "Data Explorer", "About"])
with tab1:
st.markdown('<p class="sub-header">Interactive Data Visualization</p>', unsafe_allow_html=True)
# Generate and display data
df = generate_data(data_size)
# Create a line chart with Plotly
fig = px.line(
df, x='date', y='value',
color='category',
color_discrete_sequence=color_themes[color_theme],
height=chart_height
)
fig.update_layout(
title="Time Series Data",
xaxis_title="Date",
yaxis_title="Value",
legend_title="Category",
hovermode="x unified"
)
st.plotly_chart(fig, use_container_width=True)
# Add some metrics
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Max Value", f"{df['value'].max():.2f}", f"{random.uniform(-10, 10):.2f}%")
with col2:
st.metric("Min Value", f"{df['value'].min():.2f}", f"{random.uniform(-10, 10):.2f}%")
with col3:
st.metric("Average", f"{df['value'].mean():.2f}", f"{random.uniform(-10, 10):.2f}%")
with col4:
st.metric("Data Points", len(df), f"{data_size - 50}")
with tab2:
st.markdown('<p class="sub-header">Data Explorer</p>', unsafe_allow_html=True)
# Filter options
st.subheader("Filter Data")
# Create columns for filters
filter_col1, filter_col2 = st.columns(2)
with filter_col1:
selected_categories = st.multiselect(
"Select Categories",
options=df['category'].unique(),
default=df['category'].unique()
)
with filter_col2:
min_val, max_val = st.slider(
"Value Range",
float(df['value'].min()),
float(df['value'].max()),
[float(df['value'].min()), float(df['value'].max())]
)
# Filter the data
filtered_df = df[
(df['category'].isin(selected_categories)) &
(df['value'] >= min_val) &
(df['value'] <= max_val)
]
# Show the filtered dataframe
st.subheader(f"Filtered Data ({len(filtered_df)} rows)")
st.dataframe(filtered_df, use_container_width=True)
# Download button
csv = filtered_df.to_csv(index=False).encode('utf-8')
st.download_button(
"Download CSV",
csv,
"filtered_data.csv",
"text/csv",
key='download-csv'
)
with tab3:
st.markdown('<p class="sub-header">About This App</p>', unsafe_allow_html=True)
st.markdown("""
This is a quick demo showcasing some of Streamlit's features:
- **Interactive Charts**: Visualize data dynamically
- **Data Filtering**: Filter and explore datasets
- **Download Capabilities**: Export data as CSV
- **Metrics & KPIs**: Display key performance indicators
- **Custom Styling**: Enhance UI with custom CSS
Streamlit makes it easy to create data apps with just a few lines of Python code.
""")
st.info("Made with ❀️ using Streamlit")
# Footer
st.markdown("---")
st.markdown("Created as a quick Streamlit demo")