Spaces:
Sleeping
Sleeping
| # -*- coding: utf-8 -*- | |
| """streamlit_altair.ipynb | |
| Automatically generated by Colab. | |
| Original file is located at | |
| https://colab.research.google.com/drive/1KiJCGzPr79u2mN7nXBz-smug7tEclhJE | |
| """ | |
| #!pip install -q streamlit | |
| # streamlit and other required libraries should be written in requirements.txt in Github repo | |
| import streamlit as st | |
| import altair as alt | |
| import numpy as np | |
| import pandas as pd | |
| from vega_datasets import data | |
| from faker import Faker | |
| # 1. Main Page Config | |
| st.set_page_config( | |
| page_title="Streamlit Multi-Page Demo", | |
| page_icon="π", | |
| layout="wide", | |
| initial_sidebar_state="expanded", | |
| ) | |
| # Sidebar Navigation Hint | |
| st.sidebar.success("λμ’ λ°μ΄λ¬ μΈμ΄μΈμ€") | |
| # Landing Page Content (Kept as per user request for markdown additions) | |
| st.title("π Streamlit Multi-Page Lab") | |
| st.markdown(""" | |
| Welcome to your integrated Streamlit workspace! This project combines multiple quickstart templates and interactive demos into a single multi-page application. | |
| ### π§ͺ Available Demos: | |
| 1. **Home (This page)**: Current Altair and Interactive Dataframe demo. | |
| 2. **π [Top Stocks](./us-stock-top-mktcap)**: Ranking of the world's largest companies by market cap with logos. | |
| 3. **π [US Top Stock Peers](./us-stock-top-compare)**: Comparative analysis of stock market peers using Yahoo Finance. | |
| 4. **πΊοΈ [GDP Dashboard](./global-gdp-compare)**: Global GDP analysis from World Bank data. | |
| 5. **π€ [Gemini File Q&A](./llm-gemini-rag)**: Document answering using Google Gemini (PDF/TXT/MD support). | |
| --- | |
| """) | |
| # Streamlit will only download the data once since the data will be saved in a cache | |
| def get_data(): | |
| source = data.stocks() | |
| source = source[source.date.gt("2006-01-01")] | |
| return source | |
| def get_profile_dataset(number_of_items: int = 20, seed: int = 0) -> pd.DataFrame: | |
| new_data = [] | |
| fake = Faker() | |
| np.random.seed(seed) | |
| Faker.seed(seed) | |
| for i in range(number_of_items): | |
| profile = fake.profile() | |
| new_data.append( | |
| { | |
| "name": profile["name"], | |
| "daily_activity": np.random.rand(25), | |
| "activity": np.random.randint(2, 90, size=12), | |
| } | |
| ) | |
| profile_df = pd.DataFrame(new_data) | |
| return profile_df | |
| ####################################### | |
| st.title("Altair") | |
| stock_data = get_data() | |
| # Events in altair | |
| # Note: selection_single is deprecated in Altair 5+, but we use selection_point for compatibility | |
| # while maintaining the original logic functionality. | |
| hover = alt.selection_point( | |
| fields=["date"], | |
| nearest=True, | |
| on="mouseover", | |
| empty=False, | |
| ) | |
| lines = ( | |
| alt.Chart(stock_data, title="Evolution of stock prices") | |
| .mark_line() | |
| .encode( | |
| x="date", | |
| y="price", | |
| color="symbol", | |
| ) | |
| ) | |
| points = lines.transform_filter(hover).mark_circle(size=65) | |
| tooltips = ( | |
| alt.Chart(stock_data) | |
| .mark_rule() | |
| .encode( | |
| x="yearmonthdate(date)", | |
| y="price", | |
| opacity=alt.condition(hover, alt.value(0.3), alt.value(0)), | |
| tooltip=[ | |
| alt.Tooltip("date", title="Date"), | |
| alt.Tooltip("price", title="Price (USD)"), | |
| ], | |
| ) | |
| .add_params(hover) | |
| ) | |
| # Combine the lines, points, and tooltips into a single chart. | |
| data_layer = lines + points + tooltips | |
| # Build the annotation layer | |
| ANNOTATIONS = [ | |
| ("Sep 01, 2007", 450, "π", "Something's going well for GOOG & AAPL."), | |
| ("Nov 01, 2008", 220, "π", "The market is recovering."), | |
| ("Dec 01, 2007", 750, "π±", "Something's going wrong for GOOG & AAPL."), | |
| ("Dec 01, 2009", 680, "π±", "A hiccup for GOOG."), | |
| ] | |
| annotations_df = pd.DataFrame( | |
| ANNOTATIONS, columns=["date", "price", "marker", "description"] | |
| ) | |
| annotations_df.date = pd.to_datetime(annotations_df.date) | |
| annotation_layer = ( | |
| alt.Chart(annotations_df) | |
| .mark_text(size=20, dx=-10, dy=0, align="left") | |
| .encode(x="date:T", y=alt.Y("price:Q"), text="marker", tooltip="description") | |
| ) | |
| # Define the combined chart. | |
| combined_chart = data_layer + annotation_layer | |
| # enable panning and zooming | |
| # combined_chart = (data_layer + annotation_layer).interactive() | |
| # Display the chart in Streamlit. | |
| st.altair_chart(combined_chart, use_container_width=True) | |
| ####################################### | |
| st.title("Get dataframe row-selections") | |
| column_configuration = { | |
| "name": st.column_config.TextColumn( | |
| "Name", help="The name of the user", max_chars=100, width="medium" | |
| ), | |
| "activity": st.column_config.LineChartColumn( | |
| "Activity (1 year)", | |
| help="The user's activity over the last 1 year", | |
| width="large", | |
| y_min=0, | |
| y_max=100, | |
| ), | |
| "daily_activity": st.column_config.BarChartColumn( | |
| "Activity (daily)", | |
| help="The user's activity in the last 25 days", | |
| width="medium", | |
| y_min=0, | |
| y_max=1, | |
| ), | |
| } | |
| select, compare = st.tabs(["Select members", "Compare selected"]) | |
| with select: | |
| st.header("All members") | |
| df = get_profile_dataset() | |
| event = st.dataframe( | |
| df, | |
| column_config=column_configuration, | |
| use_container_width=True, | |
| hide_index=True, | |
| on_select="rerun", | |
| selection_mode="multi-row", | |
| ) | |
| st.header("Selected members") | |
| people = event.selection.rows | |
| filtered_df = df.iloc[people] | |
| st.dataframe( | |
| filtered_df, | |
| column_config=column_configuration, | |
| use_container_width=True, | |
| ) | |
| with compare: | |
| activity_df = {} | |
| for person in people: | |
| activity_df[df.iloc[person]["name"]] = df.iloc[person]["activity"] | |
| activity_df = pd.DataFrame(activity_df) | |
| daily_activity_df = {} | |
| for person in people: | |
| daily_activity_df[df.iloc[person]["name"]] = df.iloc[person]["daily_activity"] | |
| daily_activity_df = pd.DataFrame(daily_activity_df) | |
| if len(people) > 0: | |
| st.header("Daily activity comparison") | |
| st.bar_chart(daily_activity_df) | |
| st.header("Yearly activity comparison") | |
| st.line_chart(activity_df) | |
| else: | |
| st.markdown("No members selected.") | |