Lashtw commited on
Commit
a3ea68d
·
verified ·
1 Parent(s): 891a6d4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -0
app.py CHANGED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import plotly.graph_objects as go
4
+ import numpy as np
5
+
6
+ def load_data(uploaded_file):
7
+ """載入並處理CSV檔案"""
8
+ try:
9
+ df = pd.read_csv(uploaded_file, encoding='utf-8')
10
+ return df
11
+ except Exception as e:
12
+ st.error(f"載入檔案時發生錯誤:{e}")
13
+ return None
14
+
15
+ def prepare_radar_data(df, selected_columns):
16
+ """準備雷達圖所需的數據"""
17
+ # 移除非數值的列
18
+ numeric_df = df.select_dtypes(include=[np.number])
19
+
20
+ # 篩選使用者選擇的欄位
21
+ selected_data = numeric_df[selected_columns]
22
+
23
+ return selected_data
24
+
25
+ def create_radar_chart(data, selected_columns):
26
+ """使用Plotly建立雷達圖"""
27
+ # 定義不同線段樣式
28
+ line_styles = ['solid', 'dot', 'dash', 'longdash', 'dashdot']
29
+
30
+ # 定義顏色調色盤
31
+ colors = ['#1F77B4', '#FF7F0E', '#2CA02C', '#D62728', '#9467BD']
32
+
33
+ fig = go.Figure()
34
+
35
+ for i, (index, row) in enumerate(data.iterrows()):
36
+ # 根據列名判斷是否為平均或標準值
37
+ if '平均' in index or '標' in index:
38
+ marker_symbol = 'star'
39
+ line_width = 3
40
+ else:
41
+ marker_symbol = 'circle'
42
+ line_width = 2
43
+
44
+ fig.add_trace(go.Scatterpolar(
45
+ r = row.values,
46
+ theta = selected_columns,
47
+ fill = 'toself',
48
+ name = index,
49
+ line = dict(
50
+ color = colors[i % len(colors)],
51
+ dash = line_styles[i % len(line_styles)],
52
+ width = line_width
53
+ ),
54
+ marker = dict(symbol=marker_symbol)
55
+ ))
56
+
57
+ fig.update_layout(
58
+ polar = dict(
59
+ radialaxis = dict(
60
+ visible = True,
61
+ range = [0, data.values.max() * 1.1]
62
+ )
63
+ ),
64
+ showlegend = True,
65
+ title = '學生成績雷達圖'
66
+ )
67
+
68
+ return fig
69
+
70
+ def main():
71
+ st.title('學生成績雷達圖產生器')
72
+
73
+ # 上傳CSV檔案
74
+ uploaded_file = st.file_uploader("上傳CSV檔案", type=['csv'])
75
+
76
+ if uploaded_file is not None:
77
+ df = load_data(uploaded_file)
78
+
79
+ if df is not None:
80
+ # 選擇要比較的欄位
81
+ numeric_columns = df.select_dtypes(include=[np.number]).columns.tolist()
82
+ selected_columns = st.multiselect('選擇要比較的欄位', numeric_columns, default=['國文', '英文', '數學'])
83
+
84
+ if selected_columns:
85
+ # 準備雷達圖數據
86
+ radar_data = prepare_radar_data(df, selected_columns)
87
+
88
+ # 建立雷達圖
89
+ fig = create_radar_chart(radar_data, selected_columns)
90
+
91
+ # 顯示圖表
92
+ st.plotly_chart(fig, use_container_width=True)
93
+
94
+ # 下載圖表
95
+ fig_bytes = fig.to_image(format="png", width=1200, height=800)
96
+ st.download_button(
97
+ label="下載雷達圖",
98
+ data=fig_bytes,
99
+ file_name="student_scores_radar_chart.png",
100
+ mime="image/png"
101
+ )
102
+
103
+ if __name__ == "__main__":
104
+ main()