File size: 4,792 Bytes
be783de |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 |
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")
|