Roberta2024's picture
Update app.py
17a30d8 verified
raw
history blame
3.61 kB
# -*- coding: utf-8 -*-
import streamlit as st
import pandas as pd
import requests
import plotly.express as px
import matplotlib.font_manager as fm
import matplotlib as mpl
import io
import time
# 確保正確的中文字符編碼
st.set_page_config(page_title="台灣中小企業ESG數據分析與揭露", page_icon=":chart_with_upwards_trend:", layout="wide")
# 定義 URL
urls = {
"溫室氣體": "https://mopsfin.twse.com.tw/opendata/t187ap46_L_1.csv",
"能源": "https://mopsfin.twse.com.tw/opendata/t187ap46_O_2.csv",
"董事會揭露": "https://mopsfin.twse.com.tw/opendata/t187ap46_L_6.csv"
}
# 下載並加載 CSV 文件到 DataFrame 的函數
@st.cache_data
def load_data(url):
response = requests.get(url)
response.encoding = 'utf-8'
df = pd.read_csv(io.StringIO(response.text), encoding='utf-8')
df = df.fillna(0)
return df
# Streamlit 應用
st.title("2024 台灣企業ESG數據分析與揭露")
st.subheader("以溫室氣體 X 再生能源 X 董事會資訊")
# 允許用戶選擇數據集
dataset_choice = st.selectbox("選擇要顯示的數據集", list(urls.keys()))
# 加載選定的數據集
selected_df = load_data(urls[dataset_choice])
# 顯示爬取的資料
st.write("### 爬取的資料預覽")
st.dataframe(selected_df.head())
# 允許用戶選擇用於繪製圖表的列
column_choice = st.selectbox("選擇欄位來繪製圖表", selected_df.columns)
# 添加一個生成圖表的按鈕
if st.button("生成圖表"):
# 顯示進度條
progress_bar = st.progress(0)
for i in range(100):
time.sleep(0.01)
progress_bar.progress(i + 1)
# 檢查該列是否為數值類型
if pd.api.types.is_numeric_dtype(selected_df[column_choice]):
# 創建一個標籤頁布局
tab1, tab2 = st.tabs(["圓餅圖", "長條圖"])
with tab1:
# 使用 plotly 創建圓餅圖
fig_pie = px.pie(selected_df, names=selected_df.index, values=column_choice,
title=f"{dataset_choice} - {column_choice} 圓餅圖",
color_discrete_sequence=px.colors.qualitative.Pastel)
fig_pie.update_traces(textposition='inside', textinfo='percent+label')
fig_pie.update_layout(
font=dict(size=14),
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1)
)
st.plotly_chart(fig_pie, use_container_width=True)
with tab2:
# 使用 plotly 創建長條圖
fig_bar = px.bar(selected_df, x=selected_df.index, y=column_choice,
title=f"{dataset_choice} - {column_choice} 長條圖",
color_discrete_sequence=px.colors.qualitative.Pastel)
fig_bar.update_layout(
xaxis_title="企業",
yaxis_title=column_choice,
font=dict(size=14),
xaxis_tickangle=-45
)
st.plotly_chart(fig_bar, use_container_width=True)
st.success("圖表生成完成!")
else:
st.error("選定的欄位不是數值類型,無法繪製圖表。")
# 下載並設置自定義字體以顯示中文字符
font_url = "https://drive.google.com/uc?id=1eGAsTN1HBpJAkeVM57_C7ccp7hbgSz3_&export=download"
font_response = requests.get(font_url)
with open("TaipeiSansTCBeta-Regular.ttf", "wb") as font_file:
font_file.write(font_response.content)
fm.fontManager.addfont("TaipeiSansTCBeta-Regular.ttf")
mpl.rc('font', family='Taipei Sans TC Beta')