1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
| # Cursor辅助创建疫情监控大屏
import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, timedelta
import requests
class COVID19Dashboard:
"""疫情实时监控大屏"""
def __init__(self):
st.set_page_config(
page_title="疫情实时监控大屏",
page_icon="🦠",
layout="wide",
initial_sidebar_state="collapsed"
)
# 自定义CSS样式
self.load_custom_css()
def load_custom_css(self):
"""加载自定义CSS样式"""
st.markdown("""
<style>
.main-header {
font-size: 2.5rem;
color: #1f77b4;
text-align: center;
padding: 1rem 0;
border-bottom: 2px solid #1f77b4;
margin-bottom: 2rem;
}
.metric-card {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 1rem;
border-radius: 10px;
color: white;
text-align: center;
margin: 0.5rem 0;
}
.alert-box {
background: #ff6b6b;
color: white;
padding: 1rem;
border-radius: 5px;
margin: 1rem 0;
}
</style>
""", unsafe_allow_html=True)
def fetch_covid_data(self):
"""获取疫情数据(模拟)"""
# 实际应用中应该调用真实的疫情数据API
import random
regions = ['北京', '上海', '广州', '深圳', '杭州', '南京', '武汉', '成都']
data = []
for region in regions:
data.append({
'region': region,
'confirmed': random.randint(100, 10000),
'cured': random.randint(50, 8000),
'deaths': random.randint(0, 100),
'risk_level': random.choice(['低风险', '中风险', '高风险']),
'last_update': datetime.now().strftime('%Y-%m-%d %H:%M')
})
return pd.DataFrame(data)
def create_overview_metrics(self, df):
"""创建概览指标卡片"""
total_confirmed = df['confirmed'].sum()
total_cured = df['cured'].sum()
total_deaths = df['deaths'].sum()
cure_rate = (total_cured / total_confirmed * 100) if total_confirmed > 0 else 0
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric(
label="累计确诊",
value=f"{total_confirmed:,}",
delta=f"+{random.randint(0, 100)}",
delta_color="inverse"
)
with col2:
st.metric(
label="累计治愈",
value=f"{total_cured:,}",
delta=f"+{random.randint(0, 50)}",
delta_color="normal"
)
with col3:
st.metric(
label="累计死亡",
value=f"{total_deaths:,}",
delta=f"+{random.randint(0, 5)}",
delta_color="inverse"
)
with col4:
st.metric(
label="治愈率",
value=f"{cure_rate:.1f}%",
delta=f"+0.{random.randint(1, 9)}%",
delta_color="normal"
)
def create_regional_chart(self, df):
"""创建地区分布图表"""
col1, col2 = st.columns(2)
with col1:
st.subheader("地区确诊分布")
fig_bar = px.bar(
df,
x='region',
y='confirmed',
color='risk_level',
color_discrete_map={
'低风险': '#2ecc71',
'中风险': '#f39c12',
'高风险': '#e74c3c'
},
title="各地区确诊病例数"
)
fig_bar.update_layout(showlegend=True)
st.plotly_chart(fig_bar, use_container_width=True)
with col2:
st.subheader("治愈率对比")
df['cure_rate'] = (df['cured'] / df['confirmed'] * 100).round(1)
fig_scatter = px.scatter(
df,
x='confirmed',
y='cure_rate',
size='cured',
color='risk_level',
hover_data=['region'],
title="确诊数量 vs 治愈率"
)
st.plotly_chart(fig_scatter, use_container_width=True)
def create_trend_chart(self):
"""创建趋势图表"""
st.subheader("疫情趋势分析")
# 生成模拟的时间序列数据
dates = pd.date_range(
start=datetime.now() - timedelta(days=30),
end=datetime.now(),
freq='D'
)
trend_data = pd.DataFrame({
'date': dates,
'confirmed': [random.randint(100, 500) for _ in range(len(dates))],
'cured': [random.randint(80, 400) for _ in range(len(dates))],
'deaths': [random.randint(0, 20) for _ in range(len(dates))]
})
# 计算累计值
trend_data['cumulative_confirmed'] = trend_data['confirmed'].cumsum()
trend_data['cumulative_cured'] = trend_data['cured'].cumsum()
trend_data['cumulative_deaths'] = trend_data['deaths'].cumsum()
fig_trend = go.Figure()
fig_trend.add_trace(go.Scatter(
x=trend_data['date'],
y=trend_data['cumulative_confirmed'],
mode='lines+markers',
name='累计确诊',
line=dict(color='#e74c3c', width=3)
))
fig_trend.add_trace(go.Scatter(
x=trend_data['date'],
y=trend_data['cumulative_cured'],
mode='lines+markers',
name='累计治愈',
line=dict(color='#2ecc71', width=3)
))
fig_trend.update_layout(
title="疫情发展趋势",
xaxis_title="日期",
yaxis_title="累计人数",
hovermode='x unified'
)
st.plotly_chart(fig_trend, use_container_width=True)
def create_risk_alerts(self, df):
"""创建风险预警"""
st.subheader("🚨 风险预警")
high_risk_regions = df[df['risk_level'] == '高风险']['region'].tolist()
if high_risk_regions:
st.error(f"高风险地区:{', '.join(high_risk_regions)}")
# 新增病例预警
recent_increase = df[df['confirmed'] > 1000]['region'].tolist()
if recent_increase:
st.warning(f"病例数较高地区:{', '.join(recent_increase)}")
# 治愈率偏低预警
df['cure_rate'] = df['cured'] / df['confirmed'] * 100
low_cure_rate = df[df['cure_rate'] < 80]['region'].tolist()
if low_cure_rate:
st.info(f"治愈率有待提升地区:{', '.join(low_cure_rate)}")
def run_dashboard(self):
"""运行仪表盘"""
st.markdown('<h1 class="main-header">🦠 疫情实时监控大屏</h1>',
unsafe_allow_html=True)
# 获取数据
df = self.fetch_covid_data()
# 显示最后更新时间
st.sidebar.info(f"最后更新:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
# 自动刷新按钮
if st.sidebar.button("🔄 刷新数据"):
st.experimental_rerun()
# 概览指标
self.create_overview_metrics(df)
# 地区分布图表
self.create_regional_chart(df)
# 趋势分析
self.create_trend_chart()
# 风险预警
self.create_risk_alerts(df)
# 详细数据表
with st.expander("📊 详细数据"):
st.dataframe(df, use_container_width=True)
# 运行应用
if __name__ == "__main__":
dashboard = COVID19Dashboard()
dashboard.run_dashboard()
|