# 导入必要库 import streamlit as st import pandas as pd import altair as alt # 数据加载函数(带缓存) @st.cache_data # 使用Streamlit缓存加速重复加载 def load_data(): # 从GitHub原始地址加载数据 url = "https://raw.githubusercontent.com/UIUC-iSchool-DataViz/is445_data/main/bfro_reports_fall2022.csv" df = pd.read_csv(url) # 日期处理(转换为datetime格式并提取年份) df['date'] = pd.to_datetime(df['date'], errors='coerce') # 转换错误设为NaT df['year'] = df['date'].dt.year # 提取年份 # 过滤无效年份(1900年之前的数据视为异常) df = df[df['year'] > 1900] return df # 主程序 def main(): # 设置页面标题 st.title("Bigfoot Sighting Analysis Report") # 加载数据 df = load_data() # --- 数据概览部分 --- st.header("Dataset Overview") st.write(f"Total records: {len(df)}") st.write(f"Time range: {int(df['year'].min())} - {int(df['year'].max())}") # --- 第一个可视化:年度趋势 --- st.header("Visualization 1: Yearly Sighting Trends") # 准备数据:按年份分组计数 yearly_counts = df.groupby('year').size().reset_index(name='counts') # 创建Altair图表 chart1 = alt.Chart(yearly_counts).mark_bar().encode( x=alt.X('year:O', title="Year"), # 离散年份 y=alt.Y('counts:Q', title="Number of Reports"), # 数量统计 color=alt.Color('year:O', legend=None), # 按年份着色 tooltip=['year', 'counts'] # 悬浮提示 ).properties( width=600, height=300 ) # 显示图表 st.altair_chart(chart1) # 图表描述(英文) st.write(""" **Yearly Trend Analysis** This bar chart shows the number of reported sightings per year. Key design choices: - Discrete years on X-axis for clear temporal segmentation - Color gradient enhances perception of time progression - Fixed bar width ensures visual consistency Potential improvements: - Add moving average line for trend visualization - Implement interactive year-range selection """) # --- 第二个可视化:各州分布 --- st.header("Visualization 2: State Distribution") # 准备数据:各州计数(取前10) state_counts = df['state'].value_counts().reset_index() state_counts.columns = ['state', 'counts'] top_states = state_counts.head(10) # 创建Altair图表 chart2 = alt.Chart(top_states).mark_bar().encode( y=alt.Y('state:N', title="State", sort='-x'), # 按数量降序排列 x=alt.X('counts:Q', title="Number of Reports"), color=alt.Color('state:N', legend=None) # 按州着色 ).properties( width=600, height=400 ) # 显示图表 st.altair_chart(chart2) # 图表描述(英文) st.write(""" **Geographic Distribution Analysis** This horizontal bar chart displays the top 10 states with most sightings. Key features: - Horizontal orientation improves state name readability - Descending sort emphasizes high-frequency states - Categorical coloring enhances visual distinction Potential improvements: - Add map-based visualization - Normalize data by population density """) # 主程序入口 if __name__ == "__main__": main()