-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
1795 lines (1545 loc) · 63.2 KB
/
Copy pathapp.py
File metadata and controls
1795 lines (1545 loc) · 63.2 KB
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import datetime
import time
import io
import warnings
warnings.filterwarnings('ignore')
# ---------- PAGE CONFIG AND THEME ----------
st.set_page_config(
page_title="COVID-19 Analytics Hub",
layout="wide",
page_icon="🦠",
initial_sidebar_state="expanded"
)
# ---------- CUSTOM CSS FOR ENHANCED STYLING ----------
# This CSS works with both Streamlit's default light and dark modes
st.markdown("""
<style>
/* Typography styles */
h1 {font-size: 2.5rem !important; font-weight: 800 !important; letter-spacing: -0.02em; margin-bottom: 0.2em !important;}
h2 {font-weight: 700 !important; letter-spacing: -0.01em; border: none; padding-bottom: 0.3em;}
h3 {font-weight: 600 !important;}
.subtitle {font-size: 1.2rem; margin-top: -1em; margin-bottom: 1em; opacity: 0.8;}
/* Cards with shadow and rounded corners */
.card {
border-radius: 12px;
padding: 1.5rem;
margin-bottom: 1.5rem;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.card:hover {
transform: translateY(-5px);
box-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
}
/* Metric cards with hover effect */
.metrics-container {
display: flex;
flex-wrap: wrap;
gap: 16px;
margin: 1rem 0 2rem 0;
}
.metric-card {
flex: 1;
min-width: 180px;
border-radius: 12px;
padding: 1.25rem;
text-align: center;
position: relative;
overflow: hidden;
transition: transform 0.3s ease, box-shadow 0.3s ease;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.metric-card:hover {
transform: translateY(-5px);
box-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
}
.metric-card.cases { border-top: 5px solid #3b82f6; }
.metric-card.deaths { border-top: 5px solid #ef4444; }
.metric-card.recovered { border-top: 5px solid #10b981; }
.metric-card.active { border-top: 5px solid #f59e0b; }
.metric-value {
font-size: 2.2rem;
font-weight: 700;
line-height: 1.2;
}
.metric-label {
font-size: 1rem;
margin-top: 0.5rem;
font-weight: 500;
opacity: 0.8;
}
.metric-change {
display: inline-block;
padding: 3px 8px;
border-radius: 12px;
font-size: 0.8rem;
margin-top: 0.5rem;
}
/* Status indicators */
.kpi-positive {background: rgba(16, 185, 129, 0.15); color: #10b981;}
.kpi-negative {background: rgba(239, 68, 68, 0.15); color: #ef4444;}
/* Enhanced tab styling */
.stTabs {
padding: 0px 4px 0px 4px !important;
}
.stTabs [data-baseweb="tab-list"] {
gap: 6px;
padding: 8px 12px;
border-radius: 12px;
}
.stTabs [data-baseweb="tab"] {
border-radius: 8px !important;
padding: 8px 16px !important;
font-weight: 500 !important;
border: none !important;
transition: all 0.3s ease;
}
/* Data badge */
.data-badge {
display: inline-flex;
align-items: center;
padding: 6px 12px;
border-radius: 20px;
font-size: 0.9rem;
font-weight: 500;
margin-bottom: 20px;
background-color: rgba(59, 130, 246, 0.1);
color: #3b82f6;
}
/* Loading animation */
.loading {
display: inline-block;
width: 18px;
height: 18px;
border: 3px solid rgba(255, 255, 255, 0.3);
border-radius: 50%;
border-top-color: currentColor;
animation: spin 1s ease-in-out infinite;
margin-right: 10px;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
/* Table styling that works with both light and dark modes */
.dataframe {
width: 100%;
border-collapse: separate !important;
border-spacing: 0 !important;
border-radius: 8px !important;
overflow: hidden !important;
}
/* Improved buttons */
.stButton>button {
border-radius: 8px;
font-weight: 600;
transition: all 0.3s ease;
}
.stButton>button:hover {
transform: translateY(-2px);
}
/* Footer */
.footer {
text-align: center;
padding: 20px 0;
margin-top: 40px;
font-size: 0.9rem;
opacity: 0.8;
border-top: 1px solid rgba(127, 127, 127, 0.2);
}
</style>
""", unsafe_allow_html=True)
# ---------- DATA LOADING WITH ERROR HANDLING ----------
@st.cache_data(ttl=3600, show_spinner=False)
def load_data(dataset_type="weekly"):
"""
Optimized data loading function with robust error handling
"""
try:
start_time = time.time()
if dataset_type == "daily":
file_path = "WHO-COVID-19-global-daily-data.csv"
df = pd.read_csv(file_path, parse_dates=['Date_reported'])
else: # weekly data
file_path = "WHO-COVID-19-global-data.csv"
df = pd.read_csv(file_path, parse_dates=['Date_reported'])
# Basic data cleaning
df['Year'] = df['Date_reported'].dt.year
df['Month'] = df['Date_reported'].dt.strftime('%b %Y')
df['Week'] = df['Date_reported'].dt.isocalendar().week
# Handle NaN values in WHO_region to fix tree map errors
df['WHO_region'] = df['WHO_region'].fillna('OTHER')
# Make sure Country has no NaN values
df['Country'] = df['Country'].fillna('Unknown')
# Calculate metrics based on data type
df = df.sort_values(['Country', 'Date_reported'])
if dataset_type == "daily":
# Daily metrics
df['New_daily_cases'] = df.groupby('Country')['Cumulative_cases'].diff().fillna(0)
df['New_daily_deaths'] = df.groupby('Country')['Cumulative_deaths'].diff().fillna(0)
# Calculate weekly metrics from daily data
df['week_id'] = df['Date_reported'].dt.strftime('%Y-%U')
weekly_aggs = df.groupby(['Country', 'WHO_region', 'week_id']).agg({
'Date_reported': 'last',
'Cumulative_cases': 'last',
'Cumulative_deaths': 'last',
'New_daily_cases': 'sum',
'New_daily_deaths': 'sum'
}).reset_index()
weekly_aggs = weekly_aggs.rename(columns={
'New_daily_cases': 'New_weekly_cases',
'New_daily_deaths': 'New_weekly_deaths'
})
# Merge weekly metrics back into daily data
df = pd.merge(
df,
weekly_aggs[['Country', 'Date_reported', 'New_weekly_cases', 'New_weekly_deaths']],
how='left',
on=['Country', 'Date_reported']
)
else:
# Weekly metrics
df['New_weekly_cases'] = df.groupby('Country')['Cumulative_cases'].diff().fillna(0)
df['New_weekly_deaths'] = df.groupby('Country')['Cumulative_deaths'].diff().fillna(0)
# Add placeholder columns for UI consistency
df['New_daily_cases'] = np.nan
df['New_daily_deaths'] = np.nan
# Fix negative values
for col in ['New_daily_cases', 'New_daily_deaths', 'New_weekly_cases', 'New_weekly_deaths']:
if col in df.columns:
df[col] = df[col].clip(lower=0)
# Calculate mortality rate
df['Mortality_rate'] = (df['Cumulative_deaths'] / df['Cumulative_cases'] * 100).round(2)
df['Mortality_rate'] = df['Mortality_rate'].fillna(0).replace([np.inf, -np.inf], 0)
# Calculate load time for performance monitoring
load_time = time.time() - start_time
return df, load_time
except Exception as e:
st.error(f"Error loading data: {e}")
return pd.DataFrame(), 0
# ---------- SIDEBAR ----------
with st.sidebar:
st.image("https://cdn-icons-png.flaticon.com/512/2913/2913465.png", width=80)
st.title("COVID-19 Analytics")
st.markdown("### Dataset Selection")
dataset_type = st.radio(
"Select Dataset Type",
["Daily", "Weekly"],
horizontal=True,
help="Daily data provides more granular analysis, weekly data offers summarized trends."
)
# Display a loading spinner while data loads
with st.spinner('Loading and processing data...'):
covid_data, load_time = load_data(dataset_type.lower())
# Show performance indicator
st.caption(f"Data loaded in {load_time:.2f} seconds")
# Continue only if data is loaded successfully
if not covid_data.empty:
# Calculate date ranges from data
min_date = covid_data['Date_reported'].min().date()
max_date = covid_data['Date_reported'].max().date()
# Date filter
st.markdown("### Date Range")
date_range = st.date_input(
"Select period:",
value=(min_date, max_date),
min_value=min_date,
max_value=max_date
)
# Handle single date selection case
if isinstance(date_range, tuple) and len(date_range) == 2:
start_date, end_date = date_range
else:
start_date = end_date = date_range
# Convert back to Timestamp for filtering
start_date_ts = pd.Timestamp(start_date)
end_date_ts = pd.Timestamp(end_date)
# Region filter
st.markdown("### Geographic Filters")
all_regions = sorted(covid_data['WHO_region'].unique())
region_filter = st.multiselect(
"WHO Region",
options=all_regions,
default=all_regions,
help="Filter by WHO region(s)"
)
# Country filter
if region_filter:
country_options = sorted(covid_data[covid_data['WHO_region'].isin(region_filter)]['Country'].unique())
else:
country_options = sorted(covid_data['Country'].unique())
country_filter = st.multiselect(
"Country",
options=country_options,
default=[],
help="Filter by specific countries (optional)"
)
# View options based on dataset type
st.markdown("### Data View")
if dataset_type == "Daily":
view_options = st.radio(
"Metric Type",
options=["Cumulative", "Daily New", "Weekly New"],
horizontal=True
)
else:
view_options = st.radio(
"Metric Type",
options=["Cumulative", "Weekly New"],
horizontal=True
)
# Visual options
st.markdown("### Visualization Options")
log_scale = st.checkbox("Use Log Scale", value=True, help="Better for comparing values of different magnitudes")
show_trends = st.checkbox("Show Trend Lines", value=True, help="Display moving averages")
# Advanced options in an expander
with st.expander("Advanced Options", expanded=False):
animation_speed = st.slider("Animation Speed", 100, 1000, 300, step=100,
help="Speed of map animations in milliseconds")
map_style = st.selectbox(
"Map Style",
["auto", "light", "dark", "satellite"],
index=0,
help="Visual theme for map displays"
)
color_theme = st.selectbox(
"Color Theme",
["Viridis", "Plasma", "Inferno", "Turbo"],
index=1,
help="Color scale for visualizations"
)
# Apply filters
with st.spinner('Applying filters...'):
filtered = covid_data[
(covid_data['Date_reported'] >= start_date_ts) &
(covid_data['Date_reported'] <= end_date_ts)
]
if region_filter:
filtered = filtered[filtered['WHO_region'].isin(region_filter)]
if country_filter:
filtered = filtered[filtered['Country'].isin(country_filter)]
else:
st.error("Failed to load data. Please check the dataset files and try again.")
st.stop()
# ---------- MAIN CONTENT ----------
# Header section with dynamic title based on selected dataset
st.markdown(f"""
# COVID-19 Global Dashboard
<div class='subtitle'>Analyzing {dataset_type} data from {start_date.strftime('%b %d, %Y')} to {end_date.strftime('%b %d, %Y')}</div>
""", unsafe_allow_html=True)
# Progress indicator while page elements load
progress_bar = st.progress(0)
# Latest date for metrics
latest_date = filtered['Date_reported'].max()
# Check if we have data after filtering
if filtered.empty:
st.warning("No data available with the current filter settings. Please adjust your filters.")
st.stop()
# Update progress
progress_bar.progress(20)
# ---------- KEY PERFORMANCE INDICATORS ----------
# Extract latest metrics
latest = filtered[filtered['Date_reported'] == latest_date]
global_cases = int(latest['Cumulative_cases'].sum())
global_deaths = int(latest['Cumulative_deaths'].sum())
affected_countries = filtered['Country'].nunique()
# Calculate changes from previous period
previous_date = filtered[filtered['Date_reported'] < latest_date]['Date_reported'].max()
if pd.notna(previous_date):
previous = filtered[filtered['Date_reported'] == previous_date]
case_change = global_cases - int(previous['Cumulative_cases'].sum())
death_change = global_deaths - int(previous['Cumulative_deaths'].sum())
case_percent = (case_change / int(previous['Cumulative_cases'].sum()) * 100) if int(previous['Cumulative_cases'].sum()) > 0 else 0
death_percent = (death_change / int(previous['Cumulative_deaths'].sum()) * 100) if int(previous['Cumulative_deaths'].sum()) > 0 else 0
else:
case_change = death_change = case_percent = death_percent = 0
# Calculate new cases based on view option
if view_options == "Daily New" and dataset_type == "Daily":
new_metric = 'New_daily_cases'
new_deaths = 'New_daily_deaths'
period = "Daily"
else:
new_metric = 'New_weekly_cases'
new_deaths = 'New_weekly_deaths'
period = "Weekly"
new_cases = int(latest[new_metric].sum())
new_deaths = int(latest[new_deaths].sum())
# Calculate mortality rate
avg_mortality = (global_deaths / global_cases * 100) if global_cases > 0 else 0
# Update progress
progress_bar.progress(30)
# Display KPI cards with enhanced styling
st.markdown('<div class="metrics-container">', unsafe_allow_html=True)
# Countries card
st.markdown(f'''
<div class="metric-card">
<div class="metric-value">{affected_countries:,}</div>
<div class="metric-label">Affected Countries</div>
</div>
''', unsafe_allow_html=True)
# Total cases card
case_class = "kpi-positive" if case_change >= 0 else "kpi-negative"
case_symbol = "+" if case_change >= 0 else ""
st.markdown(f'''
<div class="metric-card cases">
<div class="metric-value">{global_cases:,}</div>
<div class="metric-label">Total Cases</div>
<span class="metric-change {case_class}">{case_symbol}{case_change:,} ({case_percent:.1f}%)</span>
</div>
''', unsafe_allow_html=True)
# Total deaths card
death_class = "kpi-negative" if death_change >= 0 else "kpi-positive"
death_symbol = "+" if death_change >= 0 else ""
st.markdown(f'''
<div class="metric-card deaths">
<div class="metric-value">{global_deaths:,}</div>
<div class="metric-label">Total Deaths</div>
<span class="metric-change {death_class}">{death_symbol}{death_change:,} ({death_percent:.1f}%)</span>
</div>
''', unsafe_allow_html=True)
# New cases card
st.markdown(f'''
<div class="metric-card active">
<div class="metric-value">{new_cases:,}</div>
<div class="metric-label">New {period} Cases</div>
</div>
''', unsafe_allow_html=True)
# Mortality card
st.markdown(f'''
<div class="metric-card recovered">
<div class="metric-value">{avg_mortality:.2f}%</div>
<div class="metric-label">Mortality Rate</div>
</div>
''', unsafe_allow_html=True)
st.markdown('</div>', unsafe_allow_html=True)
# Display last updated badge
st.markdown(f'''
<div class="data-badge">
<div class="loading"></div> Last updated: {latest_date.strftime("%B %d, %Y")}
</div>
''', unsafe_allow_html=True)
# Update progress
progress_bar.progress(40)
# ---------- ENHANCED TAB NAVIGATION ----------
tab_icons = {
"map": "🗺️",
"countries": "📊",
"trends": "📈",
"regional": "🌐",
"explorer": "🔍",
"data": "📋"
}
# Create modern tab navigation
tabs = st.tabs([
f"{tab_icons['map']} Animated Map",
f"{tab_icons['countries']} Top Countries",
f"{tab_icons['trends']} Trends",
f"{tab_icons['regional']} Regional Analysis",
f"{tab_icons['explorer']} Explorer",
f"{tab_icons['data']} Data Table"
])
# ---------- ANIMATED MAP TAB ----------
with tabs[0]:
st.markdown('<div class="card">', unsafe_allow_html=True)
st.header("Global COVID-19 Spread")
# Create map data
map_data = filtered.copy()
map_data['date'] = map_data['Date_reported'].dt.strftime('%m/%d/%Y')
# Determine metrics based on view option
if view_options == "Cumulative":
map_metric = "Cumulative_cases"
map_deaths = "Cumulative_deaths"
title_metric = "Cumulative Cases"
elif view_options == "Daily New" and dataset_type == "Daily":
map_metric = "New_daily_cases"
map_deaths = "New_daily_deaths"
title_metric = "New Daily Cases"
else: # Weekly New
map_metric = "New_weekly_cases"
map_deaths = "New_weekly_deaths"
title_metric = "New Weekly Cases"
# Make bubble sizes more visually appealing
map_data['size'] = map_data[map_metric].clip(lower=1).pow(0.3)
# Get ordered dates for animation
ordered_dates = sorted(map_data['date'].unique(), key=lambda x: pd.to_datetime(x, format='%m/%d/%Y'))
# Sample dates to reduce frame count for smoother animations
if len(ordered_dates) > 30:
sample_step = len(ordered_dates) // 30
sampled_dates = ordered_dates[::sample_step]
if ordered_dates[-1] not in sampled_dates:
sampled_dates.append(ordered_dates[-1])
else:
sampled_dates = ordered_dates
# Create map with selected color theme
fig_map = px.scatter_geo(
map_data,
locations="Country",
locationmode='country names',
color=map_metric,
size='size',
hover_name="Country",
hover_data={
map_metric: True,
map_deaths: True,
"Mortality_rate": True,
"size": False
},
projection="natural earth",
animation_frame="date",
title=f'COVID-19: {title_metric} Over Time',
color_continuous_scale=color_theme.lower(),
range_color=[0, map_data[map_metric].quantile(0.95)] # Use 95th percentile for better contrast
)
# Determine if we should use dark mode for map
# Use Streamlit's config to determine if we're in dark mode
is_dark_theme = st.get_option("theme.base") == "dark"
# Set map styling based on user selection or theme
if map_style == "dark" or (map_style == "auto" and is_dark_theme):
bgcolor = "rgba(30,30,40,0.95)"
landcolor = "#252c36"
oceancolor = "#121418"
textcolor = "white"
template = "plotly_dark"
elif map_style == "light" or (map_style == "auto" and not is_dark_theme):
bgcolor = "rgba(240,242,246,0.95)"
landcolor = "#ebedf0"
oceancolor = "#f7f8fa"
textcolor = "black"
template = "plotly_white"
else: # satellite
bgcolor = "rgba(30,30,40,0.95)"
landcolor = "#3b3b3b"
oceancolor = "#111111"
textcolor = "white"
template = "plotly_dark"
# Enhance map appearance
fig_map.update_layout(
template=template,
paper_bgcolor=bgcolor,
geo=dict(
showland=True,
landcolor=landcolor,
showocean=True,
oceancolor=oceancolor,
showcountries=True,
countrycolor="#666666",
showcoastlines=False,
projection_type="natural earth",
showframe=False
),
height=620,
updatemenus=[{
"buttons": [
{
"args": [None, {"frame": {"duration": animation_speed, "redraw": True}, "fromcurrent": True}],
"label": "▶",
"method": "animate"
},
{
"args": [[None], {"frame": {"duration": 0, "redraw": False}, "mode": "immediate"}],
"label": "■",
"method": "animate"
}
],
"direction": "left",
"pad": {"r": 10, "t": 10},
"showactive": False,
"type": "buttons",
"x": 0.1,
"y": 0,
"bgcolor": "rgba(100,100,100,0.5)",
"font": {"color": textcolor}
}],
sliders=[{
"active": 0,
"yanchor": "top",
"xanchor": "left",
"currentvalue": {
"font": {"size": 16, "color": textcolor},
"prefix": "Date: ",
"visible": True,
"xanchor": "right"
},
"transition": {"duration": animation_speed},
"pad": {"b": 10, "t": 50},
"len": 0.9,
"x": 0.1,
"y": 0,
"steps": [
{
"args": [
[date],
{"frame": {"duration": animation_speed, "redraw": True}, "mode": "immediate"}
],
"label": date,
"method": "animate"
} for date in sampled_dates # Use sampled dates for better performance
]
}]
)
# Only create frames for sampled dates to improve performance
map_data_sampled = map_data[map_data['date'].isin(sampled_dates)]
fig_map.frames = [
go.Frame(
data=[go.Scattergeo(
locations=map_data_sampled[map_data_sampled['date'] == date]['Country'],
locationmode='country names',
marker=dict(
size=map_data_sampled[map_data_sampled['date'] == date]['size'],
color=map_data_sampled[map_data_sampled['date'] == date][map_metric],
colorscale=color_theme.lower(),
colorbar=dict(title=map_metric),
cmin=0,
cmax=map_data[map_metric].quantile(0.95)
)
)],
name=date
)
for date in sampled_dates
]
# Render map with loading indicator
with st.spinner("Rendering map..."):
st.plotly_chart(fig_map, use_container_width=True)
st.info("💡 **Pro Tip:** Use the play button to animate the map through time, or click on specific dates in the slider to jump to that point.")
st.markdown('</div>', unsafe_allow_html=True)
# Update progress
progress_bar.progress(60)
# ---------- TOP COUNTRIES TAB ----------
with tabs[1]:
st.markdown('<div class="card">', unsafe_allow_html=True)
st.header("Top Countries Analysis")
# Get metrics based on selected view
if view_options == "Cumulative":
top_metrics = ['Cumulative_cases', 'Cumulative_deaths']
title_prefix = "Cumulative"
elif view_options == "Daily New" and dataset_type == "Daily":
top_metrics = ['New_daily_cases', 'New_daily_deaths']
title_prefix = "New Daily"
else: # Weekly New
top_metrics = ['New_weekly_cases', 'New_weekly_deaths']
title_prefix = "New Weekly"
# Get data for the latest date for each country
latest_by_country = filtered.sort_values('Date_reported').groupby('Country').last().reset_index()
# Find top 10 countries by cases
top_by_cases = latest_by_country.sort_values(top_metrics[0], ascending=False).head(10)
top_by_cases['Mortality_rate'] = (top_by_cases['Cumulative_deaths'] / top_by_cases['Cumulative_cases'] * 100).round(2)
col_top1, col_top2 = st.columns(2)
with col_top1:
# Enhanced bar chart for cases
fig_topcases = px.bar(
top_by_cases,
x='Country',
y=top_metrics[0],
color=top_metrics[0],
color_continuous_scale='Blues',
title=f"Top 10 Countries by {title_prefix} Cases",
log_y=log_scale,
text=top_metrics[0],
height=450
)
fig_topcases.update_layout(
xaxis_title="",
yaxis_title=f"{title_prefix} Case Count",
coloraxis_showscale=False,
margin=dict(l=40, r=20, t=40, b=40),
)
# Format the value labels
fig_topcases.update_traces(
texttemplate='%{y:,.0f}',
textposition='outside',
textfont_size=10,
hovertemplate='<b>%{x}</b><br>Cases: %{y:,.0f}<extra></extra>'
)
st.plotly_chart(fig_topcases, use_container_width=True)
with col_top2:
# Enhanced bar chart for deaths
fig_topdeaths = px.bar(
top_by_cases,
x='Country',
y=top_metrics[1],
color=top_metrics[1],
color_continuous_scale='Reds',
title=f"{title_prefix} Deaths in Top 10 Case Countries",
log_y=log_scale,
text=top_metrics[1],
height=450
)
fig_topdeaths.update_layout(
xaxis_title="",
yaxis_title=f"{title_prefix} Death Count",
coloraxis_showscale=False,
margin=dict(l=40, r=20, t=40, b=40),
)
# Format the value labels
fig_topdeaths.update_traces(
texttemplate='%{y:,.0f}',
textposition='outside',
textfont_size=10,
hovertemplate='<b>%{x}</b><br>Deaths: %{y:,.0f}<extra></extra>'
)
st.plotly_chart(fig_topdeaths, use_container_width=True)
# Create mortality rate visualization
st.subheader("Mortality Rate Analysis")
# Create scatter plot comparing cases, deaths and mortality rate
fig_scatter = px.scatter(
top_by_cases,
x='Cumulative_cases',
y='Cumulative_deaths',
color='Mortality_rate',
size='Mortality_rate',
hover_name='Country',
text='Country',
log_x=log_scale,
log_y=log_scale,
title="Case-Death Relationship & Mortality Rate",
color_continuous_scale=color_theme.lower(),
height=500
)
fig_scatter.update_layout(
xaxis_title="Total Cases",
yaxis_title="Total Deaths",
coloraxis_colorbar=dict(title="Mortality Rate (%)"),
hovermode='closest'
)
fig_scatter.update_traces(
textposition='top center',
marker=dict(sizemin=5, sizeref=0.1),
hovertemplate='<b>%{hovertext}</b><br>Cases: %{x:,.0f}<br>Deaths: %{y:,.0f}<br>Mortality: %{marker.color:.2f}%<extra></extra>'
)
st.plotly_chart(fig_scatter, use_container_width=True)
# Mortality rate bar chart
fig_mortality = px.bar(
top_by_cases.sort_values('Mortality_rate', ascending=False),
x='Country',
y='Mortality_rate',
color='Mortality_rate',
color_continuous_scale='Viridis',
title="Mortality Rate (%) in Top 10 Countries",
text='Mortality_rate',
height=450
)
fig_mortality.update_layout(
xaxis_title="",
yaxis_title="Mortality Rate (%)",
coloraxis_showscale=False
)
fig_mortality.update_traces(
texttemplate='%{y:.2f}%',
textposition='outside',
textfont_size=10,
hovertemplate='<b>%{x}</b><br>Mortality Rate: %{y:.2f}%<extra></extra>'
)
st.plotly_chart(fig_mortality, use_container_width=True)
st.markdown('</div>', unsafe_allow_html=True)
# Update progress
progress_bar.progress(70)
# ---------- TRENDS TAB ----------
with tabs[2]:
st.markdown('<div class="card">', unsafe_allow_html=True)
st.header("Global Trends Over Time")
# Create timeline data - optimize by grouping first
timeline_metrics = {
'Cumulative_cases': 'sum',
'Cumulative_deaths': 'sum',
}
# Add appropriate metrics based on dataset type
if dataset_type == "Daily":
timeline_metrics.update({
'New_daily_cases': 'sum',
'New_daily_deaths': 'sum',
'New_weekly_cases': 'sum',
'New_weekly_deaths': 'sum'
})
else:
timeline_metrics.update({
'New_weekly_cases': 'sum',
'New_weekly_deaths': 'sum'
})
# Calculate aggregates more efficiently
with st.spinner("Calculating trends..."):
timeline = filtered.groupby('Date_reported').agg(timeline_metrics).reset_index()
timeline = timeline.sort_values('Date_reported')
# Calculate moving averages for trend lines if enabled
if show_trends:
window_size = 7 if dataset_type == "Daily" else 4
if len(timeline) >= window_size:
if dataset_type == "Daily" and 'New_daily_cases' in timeline.columns:
timeline['Cases_MA'] = timeline['New_daily_cases'].rolling(window=window_size, min_periods=1).mean()
timeline['Deaths_MA'] = timeline['New_daily_deaths'].rolling(window=window_size, min_periods=1).mean()
if 'New_weekly_cases' in timeline.columns:
timeline['Weekly_Cases_MA'] = timeline['New_weekly_cases'].rolling(window=min(window_size, len(timeline)//2 or 1), min_periods=1).mean()
timeline['Weekly_Deaths_MA'] = timeline['New_weekly_deaths'].rolling(window=min(window_size, len(timeline)//2 or 1), min_periods=1).mean()
# Create interactive time series charts based on view options
if view_options == "Cumulative":
# Cumulative cases and deaths chart
fig_cumulative = make_subplots(specs=[[{"secondary_y": True}]])
# Add traces with attractive styling
fig_cumulative.add_trace(
go.Scatter(
x=timeline['Date_reported'],
y=timeline['Cumulative_cases'],
name="Total Cases",
line=dict(color="#3b82f6", width=3, shape='spline'),
fill='tozeroy',
fillcolor='rgba(59, 130, 246, 0.2)'
)
)
fig_cumulative.add_trace(
go.Scatter(
x=timeline['Date_reported'],
y=timeline['Cumulative_deaths'],
name="Total Deaths",
line=dict(color="#ef4444", width=3, shape='spline'),
fill='tozeroy',
fillcolor='rgba(239, 68, 68, 0.2)'
),
secondary_y=True
)
# Update layout with modern styling
fig_cumulative.update_layout(
title=f"Cumulative Cases and Deaths ({dataset_type} Data)",
height=500,
hovermode="x unified",
legend=dict(
orientation="h",
yanchor="bottom",
y=1.02,
xanchor="right",
x=1
),
margin=dict(l=20, r=20, t=40, b=20),
)
# Update axes
fig_cumulative.update_yaxes(
title_text="Cumulative Cases",
secondary_y=False,
showgrid=True,
gridcolor='rgba(200, 200, 200, 0.2)',
type='linear' if not log_scale else 'log'
)
fig_cumulative.update_yaxes(
title_text="Cumulative Deaths",
secondary_y=True,
showgrid=False,
type='linear' if not log_scale else 'log'
)
fig_cumulative.update_xaxes(
title_text="Date",
showgrid=True,
gridcolor='rgba(200, 200, 200, 0.2)',
)
# Add hover template for better interaction
fig_cumulative.update_traces(
hovertemplate='<b>%{x|%B %d, %Y}</b><br>%{y:,.0f}<extra>%{fullData.name}</extra>'
)
st.plotly_chart(fig_cumulative, use_container_width=True)
elif view_options == "Daily New" and dataset_type == "Daily":
# Daily new cases and deaths chart
fig_daily = make_subplots(specs=[[{"secondary_y": True}]])
# Add bar traces for new cases and deaths
fig_daily.add_trace(
go.Bar(
x=timeline['Date_reported'],
y=timeline['New_daily_cases'],
name="New Daily Cases",
marker_color='rgba(59, 130, 246, 0.7)'
)
)
fig_daily.add_trace(
go.Bar(
x=timeline['Date_reported'],
y=timeline['New_daily_deaths'],
name="New Daily Deaths",
marker_color='rgba(239, 68, 68, 0.7)'
),
secondary_y=True
)
# Add trend lines if enabled
if show_trends and 'Cases_MA' in timeline.columns:
fig_daily.add_trace(
go.Scatter(
x=timeline['Date_reported'],
y=timeline['Cases_MA'],
name="Cases Trend (7-day MA)",
line=dict(color="#1e40af", width=3, dash='solid')