-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcovid_dashboard_owid.py
1909 lines (1606 loc) · 65.1 KB
/
covid_dashboard_owid.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
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
from numpy.core.numeric import NaN
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.cm as cm
import matplotlib.dates as mdates
from textwrap import wrap
# import seaborn as sn
from scipy import stats
import datetime as dt
from datetime import datetime, timedelta
import json
# from matplotlib.backends.backend_agg import RendererAgg
from matplotlib.font_manager import FontProperties
from matplotlib.ticker import MultipleLocator, FormatStrFormatter, AutoMinorLocator
import matplotlib.ticker as ticker
import math
import platform
# _lock = RendererAgg.lock
from scipy.signal import savgol_filter
from sklearn.metrics import r2_score
import streamlit as st
import urllib
import urllib.request
from pathlib import Path
#from streamlit import caching
from inspect import currentframe, getframeinfo
###################################################################
def download_data_file(url, filename, delimiter_, fileformat):
"""Download the external datafiles
IN : url : the url
filename : the filename (without extension) to export the file
delimiter : delimiter
fileformat : fileformat
OUT : df_temp : the dataframe
"""
# df_temp = None
download = True
with st.spinner(f"Downloading...{url}"):
if download: # download from the internet
url = url
elif fileformat == "json":
url = INPUT_DIR + filename + ".json"
else:
url = INPUT_DIR + filename + ".csv"
if fileformat == "csv":
df_temp = pd.read_csv(url, delimiter=delimiter_, low_memory=False)
elif fileformat == "json":
df_temp = pd.read_json(url)
# elif fileformat =='json_x': # workaround for NICE IC data
# pass
# # with urllib.request.urlopen(url) as url_x:
# # datajson = json.loads(url_x.read().decode())
# # for a in datajson:
# # df_temp = pd.json_normalize(a)
else:
st.error("Error in fileformat")
st.stop()
df_temp = df_temp.drop_duplicates()
# df_temp = df_temp.replace({pd.np.nan: None}) Let it to test
save_df(df_temp, filename)
return df_temp
@st.cache_data(ttl=60 * 60 * 24)
def get_data():
"""Get the data from various sources
In : -
Out : df : dataframe
UPDATETIME : Date and time from the last update"""
with st.spinner(f"GETTING ALL DATA ..."):
init()
# #CONFIG
if platform.processor() != "":
data = [
{
"url": "C:\\Users\\rcxsm\\Documents\\python_scripts\\covid19_seir_models\\COVIDcases\\input\\owid-covid-data.csv",
"name": "owid",
"delimiter": ",",
"key": "date",
"key2": "location",
"dateformat": "%Y-%m-%d",
"groupby": None,
"fileformat": "csv",
"where_field": None,
"where_criterium": None
},
{
"url": "C:\\Users\\rcxsm\\Documents\\python_scripts\\covid19_seir_models\\COVIDcases\\input\\waze_mobility.csv",
"name": "waze",
"delimiter": ",",
"key": "date",
"key2": "country",
"dateformat": "%Y-%m-%d",
"groupby": None,
"fileformat": "csv",
"where_field": "geo_type",
"where_criterium": "country"
},
{
"url": "C:\\Users\\rcxsm\\Documents\\python_scripts\\covid19_seir_models\\COVIDcases\\input\\google_mob_world.csv",
"name": "googlemobility",
"delimiter": ",",
"key": "date",
"key2": "country_region",
"dateformat": "%Y-%m-%d",
"groupby": None,
"fileformat": "csv",
"where_field": None,
"where_criterium": None
}
]
else:
data = [
{
"url": "https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/owid-covid-data.csv",
"name": "owid",
"delimiter": ",",
"key": "date",
"key2": "location",
"dateformat": "%Y-%m-%d",
"groupby": None,
"fileformat": "csv",
"where_field": None,
"where_criterium": None
},
{
"url": "https://raw.githubusercontent.com/ActiveConclusion/COVID19_mobility/master/waze_reports/waze_mobility.csv",
"name": "waze",
"delimiter": ",",
"key": "date",
"key2": "country",
"dateformat": "%Y-%m-%d",
"groupby": None,
"fileformat": "csv",
"where_field": "geo_type",
"where_criterium": "country"
},
{
"url": "https://raw.githubusercontent.com/rcsmit/COVIDcases/main/input/google_mob_world.csv",
# https://www.gstatic.com/covid19/mobility/Global_Mobility_Report.csv
"name": "googlemobility",
"delimiter": ",",
"key": "date",
"key2": "country_region",
"dateformat": "%Y-%m-%d",
"groupby": None,
"fileformat": "csv",
"where_field": None,
"where_criterium": None
},
]
type_of_join = "outer"
d = 0
# Read first datafile
df_temp_x = download_data_file(
data[d]["url"], data[d]["name"], data[d]["delimiter"], data[d]["fileformat"]
)
# df_temp_x = df_temp_x.replace({pd.np.nan: None})
df_temp_x[data[d]["key"]] = pd.to_datetime(
df_temp_x[data[d]["key"]], format=data[d]["dateformat"]
)
firstkey = data[d]["key"]
firstkey2 = data[d]["key2"]
if data[d]["where_field"] != None:
where_field = data[d]["where_field"]
df_temp_x = df_temp_x.loc[df_temp_x[where_field] == data[d]["where_criterium"]]
if data[d]["groupby"] is None:
df_temp_x = df_temp_x.sort_values(by=firstkey)
df_ungrouped = None
else:
df_temp_x = (
df_temp_x.groupby([data[d]["key"]], sort=True).sum().reset_index()
)
df_ungrouped = df_temp_x.reset_index()
firstkey_ungrouped = data[d]["key"]
df_temp = (
df_temp_x # df_temp is the base to which the other databases are merged to
)
# Read the other files
for d in range(1, len(data)):
df_temp_x = download_data_file(
data[d]["url"],
data[d]["name"],
data[d]["delimiter"],
data[d]["fileformat"],
)
# df_temp_x = df_temp_x.replace({pd.np.nan: None})
oldkey = data[d]["key"]
newkey = "key" + str(d)
oldkey2 = data[d]["key2"]
newkey2 = "key2_" + str(d)
df_temp_x = df_temp_x.rename(columns={oldkey: newkey})
df_temp_x = df_temp_x.rename(columns={oldkey2: newkey2})
#st.write (df_temp_x.dtypes)
try:
df_temp_x[newkey] = pd.to_datetime(df_temp_x[newkey], format=data[d]["dateformat"] )
except:
st.error(f"error in {oldkey} {newkey}")
st.stop()
if data[d]["where_field"] != None:
where_field = data[d]["where_field"]
df_temp_x = df_temp_x.loc[df_temp_x[where_field] == data[d]["where_criterium"]]
if data[d]["groupby"] != None:
if df_ungrouped is not None:
df_ungrouped = df_ungrouped.append(df_temp_x, ignore_index=True)
print(df_ungrouped.dtypes)
print(firstkey_ungrouped)
print(newkey)
df_ungrouped.loc[
df_ungrouped[firstkey_ungrouped].isnull(), firstkey_ungrouped
] = df_ungrouped[newkey]
else:
df_ungrouped = df_temp_x.reset_index()
firstkey_ungrouped = newkey
df_temp_x = df_temp_x.groupby([newkey], sort=True).sum().reset_index()
df_temp = pd.merge(
df_temp, df_temp_x, how=type_of_join, left_on=[firstkey, firstkey2], right_on=[newkey, newkey2]
)
df_temp.loc[df_temp[firstkey].isnull(), firstkey] = df_temp[newkey]
df_temp = df_temp.sort_values(by=firstkey)
# the tool is build around "date"
df = df_temp.rename(columns={firstkey: "date"})
UPDATETIME = datetime.now()
return df, df_ungrouped, UPDATETIME
def prepare_google_mob_worlddata():
""" Bringing back a file of 549 MB to 9 MB. Works only locally"""
# original location https://www.gstatic.com/covid19/mobility/Global_Mobility_Report.csv
url = "C:\\Users\\rcxsm\\Documents\\python_scripts\\covid19_seir_models\\input\\Global_Mobility_Report.csv"
df = pd.read_csv(url, delimiter=",", low_memory=False)
print (df)
#df = df.loc[df['sub_region_1'] == None]
df = df[df.sub_region_1.isnull()]
print (df)
name_ = "C:\\Users\\rcxsm\\Documents\\python_scripts\\covid19_seir_models\\input\\google_mob_world.csv"
compression_opts = dict(method=None, archive_name=name_)
df.to_csv(name_, index=False, compression=compression_opts)
print("--- Saving " + name_ + " ---")
def week_to_week(df, column_):
column_ = column_ if type(column_) == list else [column_]
newcolumns = []
newcolumns2 = []
df = df.reset_index()
for c in column_:
newname = str(c) + "_weekdiff"
newname2 = str(c) + "_weekdiff_index"
newcolumns.append(newname)
newcolumns2.append(newname2)
df[newname] = np.nan
df[newname2] = np.nan
for n in range(11, len(df)):
vorige_week = df.iloc[n - 7][c]
nu = df.iloc[n][c]
index = df.iloc[n]["index"]
# st.write(f"{c} - {n}-{vorige_week} - {nu}")
waarde = round((((nu - vorige_week) / vorige_week) * 100), 2)
waarde2 = round((((nu) / vorige_week) * 100), 2)
#st.write(f"{c} - {n} - {index} -{vorige_week} - {nu} - diff {waarde} - diff index{waarde2}")
df.iloc[n, df.columns.get_loc(newname) ] = waarde
df.iloc[n, df.columns.get_loc(newname2)] = waarde2
return df, newcolumns, newcolumns2
def rh2q(rh, t, p ):
# https://archive.eol.ucar.edu/projects/ceop/dm/documents/refdata_report/eqns.html
#Td = math.log(e/6.112)*243.5/(17.67-math.log(e/6.112))
es = 6.112 * math.exp((17.67 * t)/(t + 243.5))
e = es * (rh / 100)
q_ = (0.622 * e)/(p - (0.378 * e)) * 1000
return round(q_,2)
def move_column(df, column_, days):
""" _ _ _ """
column_ = column_ if type(column_) == list else [column_]
for column in column_:
new_column = column + "_moved_" + str(days)
df[new_column] = df[column].shift(days)
return df, new_column
def move_columnlist(df, column_, days):
""" _ _ _ """
column_ = column_ if type(column_) == list else [column_]
moved_columns = []
for column in column_:
new_column = column + "_moved_" + str(days)
df[new_column] = df[column].shift(days)
moved_columns.append(new_column)
return df, moved_columns
def drop_columns(df, what_to_drop):
""" _ _ _ """
if what_to_drop != None:
for d in what_to_drop:
print("dropping " + d)
df = df.drop(columns=[d], axis=1)
return df
def select_period(df, show_from, show_until):
""" _ _ _ """
if show_from is None:
show_from = "2020-1-1"
if show_until is None:
show_until = "2030-1-1"
mask = (df["date"].dt.date >= show_from) & (df["date"].dt.date <= show_until)
df = df.loc[mask]
df = df.reset_index()
return df
def agg_week(df, how):
""" _ _ _ """
# #TODO
# HERE ARE SOME PROBLEMS DUE TO MISSING .isotype()
# FutureWarning: Series.dt.weekofyear and Series.dt.week have been deprecated.
# Please use Series.dt.isocalendar().week instead.
df["weeknr"] = df["date"].dt.week
df["yearnr"] = df["date"].dt.year
df["weekalt"] = (
df["date"].dt.year.astype(str) + "-" + df["date"].dt.week.astype(str)
)
for i in range(len(df)):
if df.iloc[i]["weekalt"] == "2021-53":
df.iloc[i]["weekalt"] = "2020-53"
# how = "mean"
if how == "mean":
dfweek = (
df.groupby(["weeknr", "yearnr", "weekalt"], sort=False).mean().reset_index()
)
elif how == "sum":
dfweek = (
df.groupby(["weeknr", "yearnr", "weekalt"], sort=False).sum().reset_index()
)
else:
print("error agg_week()")
st.stop()
return df, dfweek
def save_df(df, name):
""" _ _ _ """
name_ = OUTPUT_DIR + name + ".csv"
compression_opts = dict(method=None, archive_name=name_)
try:
df.to_csv(name_, index=False, compression=compression_opts)
print("--- Saving " + name_ + " ---")
except:
print("--- ERROR IN Saving " + name_ + " ---")
##########################################################
def correlation_matrix(df, werkdagen, weekend_):
""" _ _ _ """
# CALCULATE CORRELATION
corrMatrix = df.corr()
sn.heatmap(corrMatrix, annot=True, annot_kws={"fontsize": 7})
plt.title("ALL DAYS", fontsize=20)
plt.show()
# corrMatrix = werkdagen.corr()
# sn.heatmap(corrMatrix, annot=True)
# plt.title("WORKING DAYS", fontsize =20)
# plt.show()
# corrMatrix = weekend_.corr()
# sn.heatmap(corrMatrix, annot=True)
# plt.title("WEEKEND", fontsize =20)
# plt.show()
# MAKE A SCATTERPLOT
# sn.regplot(y="Rt_avg", x="Kliniek_Nieuwe_Opnames_COVID", data=df)
# plt.show()
def normeren(df, what_to_norm):
"""In : columlijst
Bewerking : max = 1
Out : columlijst met genormeerde kolommen"""
# print(df.dtypes)
normed_columns = []
for column in what_to_norm:
maxvalue = (df[column].max()) / 100
firstvalue = df[column].iloc[int(WDW2 / 2)] / 100
name = f"{column}_normed"
for i in range(len(df)):
if how_to_norm == "max":
df.loc[i, name] = df.loc[i, column] / maxvalue
else:
df.loc[i, name] = df.loc[i, column] / firstvalue
normed_columns.append(name)
print(f"{name} generated")
return df, normed_columns
def graph_daily_normed(
df, what_to_show_day_l, what_to_show_day_r, how_to_smoothen, how_to_display
):
"""IN : df, de kolommen die genormeerd moeten worden
ACTION : de grafieken met de genormeerde kolommen tonen"""
if what_to_show_day_l is None:
st.warning("Choose something")
st.stop()
df, smoothed_columns_l = smooth_columnlist(df, what_to_show_day_l, how_to_smoothen,WDW2, centersmooth)
df, normed_columns_l = normeren(df, smoothed_columns_l)
df, smoothed_columns_r = smooth_columnlist(df, what_to_show_day_r, how_to_smoothen, WDW2, centersmooth)
df, normed_columns_r = normeren(df, smoothed_columns_r)
graph_daily(df, normed_columns_l, normed_columns_r, None, how_to_display)
def graph_day(df, what_to_show_l, what_to_show_r, how_to_smooth, title, t):
""" _ _ _ """
#st.write(f"t = {t}")
df_temp = pd.DataFrame(columns=["date"])
if what_to_show_l is None:
st.warning("Choose something")
st.stop()
if type(what_to_show_l) == list:
what_to_show_l_ = what_to_show_l
else:
what_to_show_l_ = [what_to_show_l]
if type(what_to_show_r) == list:
what_to_show_r_ = what_to_show_r
else:
what_to_show_r_ = [what_to_show_r]
aantal = len(what_to_show_l_)
# SHOW A GRAPH IN TIME / DAY
#with _lock:
if 1==1:
fig1x = plt.figure()
ax = fig1x.add_subplot(111)
# Some nice colors chosen with coolors.com
# #CONFIG
bittersweet = "#ff6666" # reddish 0
operamauve = "#ac80a0" # purple 1
green_pigment = "#3fa34d" # green 2
minion_yellow = "#EAD94C" # yellow 3
mariagold = "#EFA00B" # orange 4
falu_red = "#7b2d26" # red 5
COLOR_weekday = "#3e5c76" # blue 6
COLOR_weekend = "#e49273" # dark salmon 7
prusian_blue = "#1D2D44" # 8
white = "#eeeeee"
color_list = [
"#02A6A8",
"#4E9148",
"#F05225",
"#024754",
"#FBAA27",
"#302823",
"#F07826",
"#ff6666", # reddish 0
"#ac80a0", # purple 1
"#3fa34d", # green 2
"#EAD94C", # yellow 3
"#EFA00B", # orange 4
"#7b2d26", # red 5
"#3e5c76", # blue 6
"#e49273", # dark salmon 7
"#1D2D44", # 8
]
n = 0 # counter to walk through the colors-list
df, columnlist_sm_l = smooth_columnlist(df, what_to_show_l_, how_to_smooth, WDW2, centersmooth)
df, columnlist_sm_r = smooth_columnlist(df, what_to_show_r_, how_to_smooth, WDW2, centersmooth)
# CODE TO MAKE STACKED BARS - DOESNT WORK
# stackon=""
# if len(what_to_show_l_)>1:
# w = ["Datum"]
# for s in what_to_show_l_:
# w.append(s)
# #st.write(w)
# df_stacked = df[w].copy()
# #print (df_stacked.dtypes)
# #df_stacked.set_index('Datum')
# st.write(df_stacked)
# if t == "bar":
# ax = df_stacked.plot.bar(stacked=True)
# ax = df_stacked.plot(rot=0)
# st.bar_chart(df_stacked)
# ax = df[c_smooth].plot(label=c_smooth, color = color_list[2],linewidth=1.5) # SMA
for b in what_to_show_l_:
# if type(a) == list:
# a_=a
# else:
# a_=[a]
# PROBEERSEL OM WEEK GEMIDDELDES MEE TE KUNNEN PLOTTEN IN DE DAGELIJKSE GRAFIEK
# dfweek_ = df.groupby('weekalt', sort=False).mean().reset_index()
# save_df(dfweek_,"whatisdftemp1")
# w = b + "_week"
# print ("============="+ w)
# df_temp = dfweek_[["weekalt",b ]]
# df_temp = df_temp(columns={b: w})
# print (df_temp.dtypes)
# #df_temp is suddenly a table with all the rows
# print (df_temp)
# save_df(df_temp,"whatisdftemp2")
if t == "bar":
# weekends have a different color
firstday = df.iloc[0]["WEEKDAY"] # monday = 0
if firstday == 0:
color_x = [
COLOR_weekday,
COLOR_weekday,
COLOR_weekday,
COLOR_weekday,
COLOR_weekday,
COLOR_weekend,
COLOR_weekend,
]
elif firstday == 1:
color_x = [
COLOR_weekday,
COLOR_weekday,
COLOR_weekday,
COLOR_weekday,
COLOR_weekend,
COLOR_weekend,
COLOR_weekday,
]
elif firstday == 2:
color_x = [
COLOR_weekday,
COLOR_weekday,
COLOR_weekday,
COLOR_weekend,
COLOR_weekend,
COLOR_weekday,
COLOR_weekday,
]
elif firstday == 3:
color_x = [
COLOR_weekday,
COLOR_weekday,
COLOR_weekend,
COLOR_weekend,
COLOR_weekday,
COLOR_weekday,
COLOR_weekday,
]
elif firstday == 4:
color_x = [
COLOR_weekday,
COLOR_weekend,
COLOR_weekend,
COLOR_weekday,
COLOR_weekday,
COLOR_weekday,
COLOR_weekday,
]
elif firstday == 5:
color_x = [
COLOR_weekend,
COLOR_weekend,
COLOR_weekday,
COLOR_weekday,
COLOR_weekday,
COLOR_weekday,
COLOR_weekday,
]
elif firstday == 6:
color_x = [
COLOR_weekend,
COLOR_weekday,
COLOR_weekday,
COLOR_weekday,
COLOR_weekday,
COLOR_weekday,
COLOR_weekend,
]
if showoneday:
if showday == 0:
color_x = [
bittersweet,
white,
white,
white,
white,
white,
white,
]
elif showday == 1:
color_x = [
white,
bittersweet,
white,
white,
white,
white,
white,
]
elif showday == 2:
color_x = [
white,
white,
bittersweet,
white,
white,
white,
white,
]
elif showday == 3:
color_x = [
white,
white,
white,
bittersweet,
white,
white,
white,
]
elif showday == 4:
color_x = [
white,
white,
white,
white,
bittersweet,
white,
white,
]
elif showday == 5:
color_x = [
white,
white,
white,
white,
white,
bittersweet,
white,
]
elif showday == 6:
color_x = [
white,
white,
white,
white,
white,
white,
bittersweet,
]
# MAYBE WE CAN LEAVE THIS OUT HERE
df, columnlist = smooth_columnlist(df, [b], how_to_smooth, WDW2, centersmooth)
df.set_index("date")
df_temp = df
if len(what_to_show_l_) == 1:
ax = df_temp[b].plot.bar(
label=b, color=color_x, alpha=0.6
) # number of cases
for c_smooth in columnlist:
ax = df[c_smooth].plot(
label=c_smooth, color=color_list[2], linewidth=1.5
) # SMA
if showR:
if show_R_value_RIVM:
ax3 = df["Rt_avg"].plot(
secondary_y=True,
linestyle="--",
label="Rt RIVM",
color=green_pigment,
alpha=0.8,
linewidth=1,
)
ax3.fill_between(
df["date"].index,
df["Rt_low"],
df["Rt_up"],
color=green_pigment,
alpha=0.2,
label="_nolegend_",
)
tgs = [3.5, 4, 5]
teller = 0
dfmin = ""
dfmax = ""
for TG in tgs:
df, R_smooth, R_smooth_sec = add_walking_r(
df, columnlist, how_to_smooth, TG
)
for R in R_smooth:
# correctie R waarde, moet naar links ivm 2x smoothen
df, Rn = move_column(df, R, MOVE_WR)
if teller == 0:
dfmin = Rn
elif teller == 1:
if show_R_value_graph:
ax3 = df[Rn].plot(
secondary_y=True,
label=Rn,
linestyle="--",
color=falu_red,
linewidth=1.2,
)
elif teller == 2:
dfmax = Rn
teller += 1
for R in R_smooth_sec: # SECOND METHOD TO CALCULATE R
# correctie R waarde, moet naar links ivm 2x smoothen
df, Rn = move_column(df, R, MOVE_WR)
# ax3=df[Rn].plot(secondary_y=True, label=Rn,linestyle='--',color=operamauve, linewidth=1)
if show_R_value_graph:
ax3.fill_between(
df["date"].index,
df[dfmin],
df[dfmax],
color=falu_red,
alpha=0.3,
label="_nolegend_",
)
else: # t = line
df_temp = df
if how_to_smooth == None:
how_to_smooth_ = "unchanged_"
else:
how_to_smooth_ = how_to_smooth + "_" + str(WDW2)
b_ = str(b) + "_" + how_to_smooth_
df_temp[b_].plot(
label=b, color=color_list[n], linewidth=1.1
) # label = b_ for uitgebreid label
df_temp[b].plot(
label="_nolegend_",
color=color_list[n],
linestyle="dotted",
alpha=0.9,
linewidth=0.8,
)
n += 1
if show_scenario == True:
df = calculate_cases(df, ry1, ry2, total_cases_0, sec_variant, extra_days)
# print (df.dtypes)
l1 = f"R = {ry1}"
l2 = f"R = {ry2}"
ax = df["variant_1"].plot(
label=l1, color=color_list[4], linestyle="dotted", linewidth=1, alpha=1
)
ax = df["variant_2"].plot(
label=l2, color=color_list[5], linestyle="dotted", linewidth=1, alpha=1
)
ax = df["variant_12"].plot(
label="TOTAL", color=color_list[6], linestyle="--", linewidth=1, alpha=1
)
if what_to_show_r != None:
if type(what_to_show_r) == list:
what_to_show_r = what_to_show_r
else:
what_to_show_r = [what_to_show_r]
n = len(color_list)
x = n
for a in what_to_show_r:
x -= 1
lbl = a + " (right ax)"
df, columnlist = smooth_columnlist(df, [a], how_to_smooth, WDW2, centersmooth)
for c_ in columnlist:
# smoothed
lbl2 = a + " (right ax)"
ax3 = df_temp[c_].plot(
secondary_y=True,
label=lbl2,
color=color_list[x],
linestyle="--",
linewidth=1.1,
) # abel = lbl2 voor uitgebreid label
ax3 = df_temp[a].plot(
secondary_y=True,
linestyle="dotted",
color=color_list[x],
linewidth=1,
alpha=0.9,
label="_nolegend_",
)
ax3.set_ylabel("_")
showlogyaxis = st.sidebar.selectbox("Y axis left log", ["No", "2", "10", "logit"], index=0)
if showlogyaxis == "10":
ax.semilogy()
if showlogyaxis == "2":
ax.semilogy(2)
if showlogyaxis == "logit":
ax.set_yscale("logit")
if len(what_to_show_l) == 1 and len(what_to_show_r) == 1: # add correlation
correlation = find_correlation_pair(df, what_to_show_l, what_to_show_r)
correlation_sm = find_correlation_pair(df, b_, c_)
title_scatter = f"{title}({str(FROM)} - {str(UNTIL)})\nCorrelation = {correlation}"
title = f"{title} \nCorrelation = {correlation}\nCorrelation smoothed = {correlation_sm}"
if len(what_to_show_r) == 1:
mean = df[what_to_show_r].mean()
std =df[what_to_show_r].std()
# print (f"mean {mean}")
# print (f"st {std}")
low = mean -2*std
up = mean +2*std
#ax3.set_ylim = (-100, 100)
plt.title(title, fontsize=10)
a__ = (max(df_temp["date"].tolist())).date() - (
min(df_temp["date"].tolist())
).date()
freq = int(a__.days / 10)
ax.xaxis.set_major_locator(MultipleLocator(freq))
if what_to_show_l == ["reported_div_tested"]:
ax.set_ylim(0,0.3)
ax.set_xticks(df_temp["date"].index)
ax.set_xticklabels(df_temp["date"].dt.date, fontsize=6, rotation=90)
xticks = ax.xaxis.get_major_ticks()
if groupby_timeperiod == "none":
for i, tick in enumerate(xticks):
if i % 10 != 0:
tick.label1.set_visible(False)
plt.xticks()
# layout of the x-axis
ax.xaxis.grid(True, which="major", alpha=0.4, linestyle="--")
ax.yaxis.grid(True, which="major", alpha=0.4, linestyle="--")
left, right = ax.get_xlim()
ax.set_xlim(left, right)
fontP = FontProperties()
fontP.set_size("xx-small")
plt.xlabel("date")
# everything in legend
# https://stackoverflow.com/questions/33611803/pyplot-single-legend-when-plotting-on-secondary-y-axis
handles, labels = [], []
for ax in fig1x.axes:
for h, l in zip(*ax.get_legend_handles_labels()):
handles.append(h)
labels.append(l)
# plt.legend(handles,labels)
# https://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot/43439132#43439132
plt.legend(handles, labels, bbox_to_anchor=(0, -0.5), loc="lower left", ncol=2)
ax.text(
1,
1.1,
"Created by Rene Smit — @rcsmit",
transform=ax.transAxes,
fontsize="xx-small",
va="top",
ha="right",
)
if show_R_value_graph or show_R_value_RIVM:
plt.axhline(y=1, color="yellow", alpha=0.6, linestyle="--")
if groupby_timeperiod == "none":
add_restrictions(df, ax)
plt.axhline(y=0, color="black", alpha=0.6, linestyle="--")
if t == "line":
set_xmargin(ax, left=-0.04, right=-0.04)
st.pyplot(fig1x)
for left in what_to_show_l:
for right in what_to_show_r:
correlation = find_correlation_pair(df, left, right)
st.write(f"Correlation: {left} - {right} : {correlation}")
for left_sm in columnlist_sm_l:
for right_sm in columnlist_sm_r:
correlation = find_correlation_pair(df, left_sm, right_sm)
st.write(f"Correlation: {left_sm} - {right_sm} : {correlation}")
if len(what_to_show_l) == 1 and len(what_to_show_r) == 1: # add scatter plot
left_sm = str(what_to_show_l[0]) + "_" + how_to_smooth_
right_sm = str(what_to_show_r[0]) + "_" + how_to_smooth_
make_scatterplot(df_temp, what_to_show_l, what_to_show_r, False)
make_scatterplot(df_temp,left_sm, right_sm, True)
def make_scatterplot(df_temp, what_to_show_l, what_to_show_r, smoothed):
if type(what_to_show_l) == list:
what_to_show_l = what_to_show_l
else:
what_to_show_l = [what_to_show_l]
if type(what_to_show_r) == list:
what_to_show_r = what_to_show_r
else:
what_to_show_r = [what_to_show_r]
#with _lock:
if 1==1:
fig1xy = plt.figure()
ax = fig1xy.add_subplot(111)
# st.write (x_)
# print (type(x_))
x_ = df_temp[what_to_show_l].values.tolist()
y_ = df_temp[what_to_show_r].values.tolist()
plt.scatter(x_, y_)
x_ = np.array(df_temp[what_to_show_l])
y_ = np.array(df_temp[what_to_show_r])
if (len(x_)==0) or (len(y_)==0):
st.error("No data")
st.stop()
try:
#obtain m (slope) and b(intercept) of linear regression line
idx = np.isfinite(x_) & np.isfinite(y_)
m, b = np.polyfit(x_[idx], y_[idx], 1)
model = np.polyfit(x_[idx], y_[idx], 1)