Spaces:
Build error
Build error
| import streamlit as st | |
| import requests | |
| import pandas as pd | |
| import plotly.express as px | |
| import matplotlib as mpl | |
| import matplotlib.font_manager as fm | |
| import os | |
| from io import StringIO | |
| def install_custom_font(): | |
| font_path = "TaipeiSansTCBeta-Regular.ttf" | |
| if not os.path.exists(font_path): | |
| font_url = "https://drive.google.com/uc?id=1eGAsTN1HBpJAkeVM57_C7ccp7hbgSz3_&export=download" | |
| font_response = requests.get(font_url) | |
| with open(font_path, "wb") as font_file: | |
| font_file.write(font_response.content) | |
| fm.fontManager.addfont(font_path) | |
| mpl.rc('font', family='Taipei Sans TC Beta') | |
| install_custom_font() | |
| st.title("ESG數據分析") | |
| # 直接讀取固定 URL 的 CSV 檔案 | |
| url = "https://mopsfin.twse.com.tw/opendata/t187ap46_L_1.csv" | |
| response = requests.get(url) | |
| response.encoding = "utf-8" | |
| df = pd.read_csv(StringIO(response.text)) | |
| df_cleaned = df.fillna(0) # 填補缺失值 | |
| st.subheader("📌 數據預覽") | |
| st.write(df_cleaned.head()) | |
| # 讓用戶篩選數據 | |
| st.subheader("🔍 數據篩選") | |
| filter_col = st.selectbox("選擇要篩選的欄位", df_cleaned.columns) | |
| unique_values = df_cleaned[filter_col].unique() | |
| selected_value = st.selectbox("選擇篩選值", unique_values) | |
| filtered_df = df_cleaned[df_cleaned[filter_col] == selected_value] | |
| st.write(filtered_df.head()) | |
| # 讓用戶選擇數值欄位 | |
| numeric_cols = filtered_df.select_dtypes(include=['number']).columns | |
| if len(numeric_cols) > 0: | |
| col_choice = st.selectbox("選擇要視覺化的數值欄位", numeric_cols) | |
| if st.button("生成圖表"): | |
| # 長條圖 | |
| st.subheader("📊 長條圖") | |
| fig_bar = px.bar(filtered_df.head(10), x=filtered_df.index[:10], y=col_choice, title=f"{col_choice} 長條圖") | |
| st.plotly_chart(fig_bar) | |
| # 圓餅圖 | |
| st.subheader("🥧 圓餅圖") | |
| fig_pie = px.pie(filtered_df.head(10), names=filtered_df.index[:10], values=col_choice, title=f"{col_choice} 圓餅圖") | |
| st.plotly_chart(fig_pie) | |
| else: | |
| st.warning("⚠ 沒有數值型欄位可供選擇") |