-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
433 lines (394 loc) · 16.5 KB
/
main.py
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
# Import libraries
import pandas as pd
import numpy as np
import requests
import geopandas as gpd
#import matplotlib.pyplot as plt
import plotly.express as px
import plotly.graph_objects as go
#import geoplot as gplt
from plotly.subplots import make_subplots
from urllib.request import urlopen
import json
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
import time
import datetime
# Custom module
from modules import data_processing
from modules import plotting
# Get county geojson for county polygones
COUNTY_GEOJSON = data_processing.load_county_geojson() # cache_mode
# Get county coronavirus data
t0=time.time()
COVID_COUNTIES_DF = data_processing.get_covid_county_data(cache_mode = 3) #cache_mode
print(f"Time for county:{time.time() - t0}")
# Get state coronavirus data
t0=time.time()
COVID_STATES_DF = data_processing.get_covid_state_data(cache_mode = 3)
print(f"Time for county:{time.time() - t0}")
date_dict = data_processing.generate_slider_dates(COVID_COUNTIES_DF)
max_date_str = time.strftime("%Y-%m-%d",time.localtime(max(date_dict)))
style_dict = {
"section-div":{
"textAlign":"center",
"border":"1px black solid",
"margin":"6px 6px 6px 6px"
},
"national-stats-item-div":{
"textAlign": "center",
"align-self":"center",
"display":"inline-block",
"border":"3px black solid",
"height":100,
"width":323,
"backgroundColor":"#D6DBDF",
"margin":"10px 10px 10px 10px"
},
"graphs":{
"textAlign":"center",
"align-self":"center",
"border":"1px black solid",
#"display":"inline-block",
"backgroundColor":"#D6DBDF",
"autosize":True,
"margin":"10px 10px 10px 10px"
},
"national-stats-container-div":{
"align-content":"center",
"border":"1px black solid",
"textAlign": "center"
}
}
################################################################################
# Create Dash object
app = dash.Dash(
external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"],
meta_tags=[
{"name": "viewport",
"content": "width=device-width, initial-scale=1"}
]
)
colors = {
"background": "#c8a2c8",# "#6495ED", #FF69B4 == pink , #c8a2c8 = lilac
"text": "#000000"#"#7FDBFF"
}
app.layout = html.Div(
style={"backgroundColor": colors["background"]},
children=[
# Title
html.Div(id="header",
children=[
html.H1(children="US Covid-19 Dash",
style={
"textAlign": "center",
"color": colors["text"]
}
), # Title H1
# Text div
html.Div(children="A dashboard to track the spread of coronavirus in the United States.",
style={
"textAlign": "center",
"color": colors["text"]
}
), #Text div
]), # close header div
html.Br(),
html.H4("National Section"),
html.Div(id="national-section",
style=style_dict["section-div"],
children=[
html.Div(id="national-stats", className="row", children=[
# Alignment is handled on this Div below.
html.Div(className="four columns",
style=style_dict['national-stats-container-div'],
children=[
html.Div(id="div-national-deaths",
style=style_dict["national-stats-item-div"],
children=[
html.H4(id="H4-national-deaths",
children=data_processing.generate_state_aggregate_stat(
COVID_STATES_DF,
max_date_str,
"death")
),
html.H5("Total Deaths")
]
),
dcc.Graph(id="graph-national-deaths",
#className="four columns",
style=style_dict['graphs'],
figure=plotting.plot_national(COVID_STATES_DF,"death"))
]),
html.Div(className="four columns",
style=style_dict['national-stats-container-div'],
children=[
html.Div(id="div-national-cases",
style=style_dict["national-stats-item-div"],
children=[
html.H4(id="H4-national-cases",
children=data_processing.generate_state_aggregate_stat(
COVID_STATES_DF,
max_date_str,
"positive")
),
html.H5("Total Positive Cases")
]
),
dcc.Graph(id="graph-national-positive",
#className="four columns",
style=style_dict['graphs'],
figure=plotting.plot_national(COVID_STATES_DF,"positive"))
]),
html.Div(className="four columns",
style=style_dict['national-stats-container-div'],
children=[
html.Div(id="div-national-hospitalizedCurrently",
style=style_dict["national-stats-item-div"],
children=[
html.H4(id="H4-national-hospitalized",
children=data_processing.generate_state_aggregate_stat(
COVID_STATES_DF,
max_date_str,
"hospitalizedCurrently")
),
html.H5("Current Hospitalization")
]
),
dcc.Graph(id="graph-national-hospitalizedCurrently",
#className="four columns",
style=style_dict['graphs'],
figure=plotting.plot_national(COVID_STATES_DF,"hospitalizedCurrently"))
])
]) # close national stats div
,html.Div(id="national-graphs", className="row",children=[])
]), # close national section div
html.Br(),
html.Div(id="debug-div"),
html.Div(id="div-slider",style={"height":"100px","border":"1px black solid"},
children=[
dcc.Slider(
id="date-slider",
min=min(date_dict),
max=max(date_dict),
value=max(date_dict),
marks=date_dict,
step=None
) # slider dcc])
]
), # slider div
html.H4("State Section"),
html.Div(id="state-section",
className="row",
style=style_dict["section-div"],
children=[
html.Div(id="state-choropleth-div",
className="six columns",
children=[
dcc.Graph(
id="state-choropleth",
style=style_dict['graphs'],
figure=plotting.plot_choropleth_state(
COVID_STATES_DF,
max_date_str,
"death"
)
)
]
),
html.Div(id="state-scatter-div",className="six columns",
children=[
dcc.Dropdown(id="state-dropdown",
value="death",
options=[
{"label":"death","value":"death"},
{"label":"deathIncrease","value":"deathIncrease"},
{"label":"positive","value":"positive"},
{"label":"positiveIncrease","value":"positiveIncrease"},
{"label":"hospitalizedCurrently","value":"hospitalizedCurrently"},
{"label":"hospitalizedCumulative","value":"hospitalizedCumulative"},
{"label":"hospitalizedIncrease", "value":"hospitalizedIncrease"}
]),
dcc.Graph(id="state-scatter",
style=style_dict['graphs'],
figure=plotting.plot_scatter_state(
COVID_STATES_DF,
"NY",
["deathIncrease","death"]
)
)
]
)
]
),
html.Br(),
# open div for county graphs
html.H4("County Section"),
html.Div(id="county-section",
className="row",
style=style_dict["section-div"],
children=[
html.Div(className="six columns",
children=[ # county choropleth div
dcc.Graph( # county choropleth graph
id="county-choropleth",
style=style_dict['graphs'],
figure=plotting.plot_choropleth_county(
COVID_COUNTIES_DF,
COUNTY_GEOJSON,
"deaths",
date = max_date_str
)
)
]
), # choropleth div
# County Scatter
html.Div(className="six columns",
children=[
dcc.Dropdown(
id="county-dropdown",
value="cases_14MA",
options=[
{"label":"Total deaths", "value":"deaths"},
{"label":"Total cases", "value":"cases"},
{"label":"Cases per million", "value":"casesPerMillion"},
{"label":"Deaths per million", "value":"deathsPerMillion"},
{"label":"Daily cases", "value":"case_diff"},
{"label":"Daily deaths", "value":"death_diff"},
#{"label":"log_cases", "value":"log_cases"},
#{"label":"log_deaths", "value":"log_deaths"},
#{"label":"log_casesPerMillion", "value":"log_casesPerMillion"},
#{"label":"log_deathsPerMillion", "value":"log_deathsPerMillion"},
{"label":"14-day MA of daily cases", "value":"cases_14MA"},
{"label":"14-day MA of daily deaths", "value":"deaths_14MA"}
]
), # close dcc dropdown
dcc.Graph(
id="county-scatter",
style=style_dict['graphs'],
figure = plotting.scatter_deaths_county(
COVID_COUNTIES_DF,
"deaths",
max_date_str,
"01001"
)
) # close dcc graph
]
), # close div tag
]
)
# ,dcc.Location(id="url", refresh=False),
# html.Link("Navigate to "/"", href="/"),
# html.Link("Navigate to "/page-2"", href="/page-2"),
# html.Div(id="page-content",children="Hello World")
])
app.title = "US Coronavirus Dashboard"
server = app.server
################################################################################
# Text OUTPUT from HOVER
@app.callback(
Output(component_id="debug-div", component_property="children"),
[Input(component_id="date-slider", component_property="value")]
)
def update_output_div(date):
date = time.strftime("%Y-%m-%d",time.localtime(date))
return f"You\'ve entered {date}"
# National Statistics
@app.callback(
Output("H4-national-deaths","children"),
[Input(component_id="date-slider", component_property="value")]
)
def update_national_stats(date):
date = time.strftime("%Y-%m-%d",time.localtime(date))
death=data_processing.generate_state_aggregate_stat(
COVID_STATES_DF,date,"death")
return death
# National Statistics
@app.callback(
Output("H4-national-cases","children"),
[Input(component_id="date-slider", component_property="value")]
)
def update_national_stats(date):
date = time.strftime("%Y-%m-%d",time.localtime(date))
positive=data_processing.generate_state_aggregate_stat(
COVID_STATES_DF,date,"positive")
return positive
# National Statistics
@app.callback(
Output("H4-national-hospitalized","children"),
[Input(component_id="date-slider", component_property="value")]
)
def update_national_stats(date):
date = time.strftime("%Y-%m-%d",time.localtime(date))
hospitalizedCurrently=data_processing.generate_state_aggregate_stat(
COVID_STATES_DF,date,"hospitalizedCurrently")
return hospitalizedCurrently
# County Choropleth
@app.callback(
Output("county-choropleth","figure"),
[Input("county-dropdown","value"),
Input("date-slider","value")]
)
def update_county_choropleth(category, date):
date = time.strftime("%Y-%m-%d",time.localtime(date))
return plotting.plot_choropleth_county(COVID_COUNTIES_DF,
COUNTY_GEOJSON,
category,
date)
# County Scatter
@app.callback(
Output(component_id="county-scatter", component_property="figure"),
[Input(component_id="county-choropleth", component_property="hoverData")],
[State(component_id="county-dropdown",component_property="value"),
State("date-slider","value")]
)
def update_county_scatter(fips_input,category,slider_date):
# Convert from epoch time to time struct to string
slider_date = time.strftime("%Y-%m-%d",time.localtime(slider_date))
try:
fips = fips_input["points"][0]["location"]
except:
fips = "01001"
# plot county scatter
scatter = plotting.scatter_deaths_county(COVID_COUNTIES_DF,category,slider_date,fips)
return scatter
# State Choropleth
@app.callback(
Output("state-choropleth","figure"),
[Input("date-slider","value"),
Input(component_id="state-dropdown",component_property="value")]
)
def update_state_choropleth(date,category):
date = time.strftime("%Y-%m-%d",time.localtime(date))
return plotting.plot_choropleth_state(COVID_STATES_DF,
date,
category)
# State Scatter
@app.callback(
Output(component_id="state-scatter", component_property="figure"),
[Input(component_id="state-choropleth", component_property="hoverData")],
[State(component_id="state-dropdown",component_property="value")]
)
def update_state_scatter(state_input,category):
# Check categories to plot daily and cumulative values for each category type
if category in ("death","deathIncrease"):
category_tuple = ("deathIncrease","death")
elif category in ("positiveIncrease","positive"):
category_tuple = ("positiveIncrease","positive")
elif category in ("hospitalizedIncrease","hospitalizedCurrently","hospitalizedCumulative"):
category_tuple = ("hospitalizedIncrease","hospitalizedCurrently")
else:
category_tuple = ("deathIncrease","death")
# Extract state string from hoverData Dict
try:
state = state_input["points"][0]["location"]
except:
state = "CA"
# Plot State Scatter
scatter = plotting.plot_scatter_state(COVID_STATES_DF, state, category_tuple)
return scatter
if __name__ == "__main__":
app.run_server(debug=True, use_reloader = True)