Spaces:
Sleeping
Sleeping
import pandas as pd | |
import requests | |
import plotly.express as px | |
import streamlit as st | |
import time | |
import matplotlib.font_manager as fm | |
import matplotlib as mpl | |
# Download and set custom font | |
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) | |
# Register the font with matplotlib | |
fm.fontManager.addfont("TaipeiSansTCBeta-Regular.ttf") | |
mpl.rc('font', family='Taipei Sans TC Beta') | |
# Function to download and load CSV into a DataFrame | |
def download_csv(url, filename): | |
response = requests.get(url) | |
with open(filename, "wb") as file: | |
file.write(response.content) | |
df = pd.read_csv(filename) | |
df = df.fillna(0) # Fill missing values with 0 | |
return df | |
# URLs to download data from | |
urls = { | |
"溫室氣體": "https://mopsfin.twse.com.tw/opendata/t187ap46_L_1.csv", # ESG | |
"再生能源": "https://mopsfin.twse.com.tw/opendata/t187ap46_O_2.csv", # Renewable Energy | |
"董事會": "https://mopsfin.twse.com.tw/opendata/t187ap46_L_6.csv" # Board of Directors | |
} | |
# Filenames to save CSV data | |
filenames = { | |
"溫室氣體": "data01.csv", | |
"再生能源": "data02.csv", | |
"董事會": "data03.csv" | |
} | |
# Streamlit app title | |
st.title("ESG Data Visualization with Streamlit") | |
# Dropdown menu for data selection | |
selected_option = st.selectbox("選擇資料類型", options=list(urls.keys())) | |
# Button to load data | |
if st.button("載入資料"): | |
with st.spinner('資料載入中...'): | |
# Simulate a delay for the process bar | |
for _ in range(5): | |
time.sleep(0.2) | |
df = download_csv(urls[selected_option], filenames[selected_option]) | |
# Displaying the DataFrame | |
st.header(f"{selected_option} 資料") | |
st.dataframe(df) | |
# Column selection for visualization | |
x_col = st.selectbox("選擇類別欄位 (X 軸)", options=df.columns) | |
y_col = st.selectbox("選擇數值欄位 (Y 軸)", options=df.columns) | |
# Chart type selection | |
chart_type = st.radio("選擇圖表類型", ("圓餅圖", "柱狀圖")) | |
# Plotting the data based on user selection | |
if chart_type == "圓餅圖": | |
fig = px.pie(df, names=x_col, values=y_col, title=f"Pie Chart for {selected_option}") | |
elif chart_type == "柱狀圖": | |
fig = px.bar(df, x=x_col, y=y_col, title=f"Bar Chart for {selected_option}") | |
# Apply custom font to the plot | |
fig.update_layout(font_family="Taipei Sans TC Beta") | |
st.plotly_chart(fig) | |