-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
3316 lines (2937 loc) · 143 KB
/
utils.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
# -*- coding: utf-8 -*-
# Dash and Plotly
import dash_html_components as html
import plotly.graph_objs as go
from plotly import tools
import pandas as pd
import numpy as np
import math
import json
from app import df
#from app import encoded_image5, encoded_image6
FREEDOM_COLORS = [["#4a386e", "#9370DB", "#b39be6", '#c9b8ed'], ["#806200", "#FFC300", "#ffd54d", '#ffe180'], ["#086405", "#10C80A", "#58d954", '#88e485']]
# ----- configurable variables -----
PLOT_HEIGHT = 400
MARKER_SIZE = 10
PLOT_COLORS = {"country": "#FF8A5B",
"region": "#38C0E1",
"men": "#F3CA40",
"women": "#6A5ACD",
"urban": "#EDC79B",
"rural": "#63A375",
"title": "#38C0E1"}
# ----- general utility functions -----
def generate_table(df_table, title=None, description=None):
"""
Generates a Dash table html component from the df_table DataFrame. The DataFrame's column names are used as headers.
generate_table() will return a div containing first a div with class table-title for the title, and then the table
itself. If title is passed, a Dash span component containing the title string will be added to the title div. If
description is passed, a Dash img component of the info icon will be added to the title div. The description will
appear when the cursor hovers over the info icon. If neither title nor description are passed, the title div will be
empty but will still be included in the returned div for consistencies sake.
:param df_table: DataFrame containing data to be formatted. Headers will be used as header names for the table.
:param title: (optional) the title string to add above the table
:param description: (optional) the description to display on cursor hover
:return: An html.Div component with an html.Div and an html.Table as children
"""
# construct table row for headers
headers = html.Tr(
children=[html.Th(col) for col in list(df_table.columns)]
)
# append table rows containing elements to headers
table_children = [headers]
for i in range(len(df_table)):
row = df_table.loc[i]
elem_list = []
for elem in row:
elem_list.append(html.Td(elem))
table_children.append(html.Tr(elem_list))
table = html.Table(
children=html.Tbody(table_children)
)
# create an empty list for children of title div
title_children = []
# add title span to title children list if title is passed
if title is not None:
title_children.append(html.Span(title))
# add info icon to title div if description is passed
if description is not None:
title_children.append(
html.Img(src='https://s3-us-west-2.amazonaws.com/da2i/Images/Info_Icon_Purple.png',
title=description)
)
# create div for title
title_div = html.Div(
className="table-title",
children=title_children
)
# wrap table in div
table_div = html.Div(
children=[title_div, table]
)
return table_div
def generate_dummy_table():
df_table = pd.DataFrame({"Column 1": ["Value 1"],
"Column 2": ["Value 2"],
"Column 3": ["Value 3"],
})
return generate_table(df_table,
title="Table Title",
description="Table description")
def generate_sparklines_slider_bar_chart(selected_country, indicator, title, categories=None):
"""
generates a sparklines style (compact) bar chart for the selected country and indicator.
:param selected_country: selected country
:param indicator: name of indicator
:param title: title of the bar chart
:param categories: a list of dicts defining the "name", "range", and "color" of categorical variables.
EX: [{"name": "category 1", "range": [lower_bound, upper_bound], "color": "#0000FF"}, ... ]
:return: sparklines bar chart
"""
#filtered data
df_filtered = df[df["Country"] == selected_country]
df_filtered = df_filtered[df_filtered["Name"] == indicator] # filtered by selected country and indicator
df_filtered = df_filtered.dropna(axis="index",subset=["value"]) # drop rows with missing indicator values
df_filtered.sort_values('Year',inplace=True)
values = df_filtered['value'].tail(1).tolist()[0] if len(df_filtered) != 0 else 'NA'
years = int(df_filtered['Year'].tail(1).tolist()[0]) if len(df_filtered) != 0 else 'NA'
if years == 'NA':
yrs_range = [2018,2018.5]
else:
yrs_range = [years,years+0.5]
if values != 'NA' and indicator == "FitW.total.aggregate.score":
# udate here
df_filtered = df[df["Country"] == selected_country]
# filtered by selected country and indicator
df_filtered = df_filtered[df_filtered["Name"] == 'FitW.total.status']
# drop rows with missing indicator values
df_filtered = df_filtered.dropna(axis="index", subset=["value"])
df_filtered.sort_values('Year', inplace=True)
status = df_filtered['value'].tail(1).tolist(
)[0] if len(df_filtered) != 0 else 'NO DATA'
if status == 1:
colors = '#10C80A'
elif status == 0.5:
colors = '#FFC300'
else:
colors = '#9370DB'
elif values != 'NA' and indicator == "FotN":
if values >= 70:
colors = '#10C80A'
elif values >= 40:
colors = '#FFC300'
else:
colors = '#9370DB'
elif values != 'NA' and indicator == "GII":
if values >= 0.7:
colors = '#FF8A5B'
elif values >= 0.3:
colors = '#FF8A5B'
else:
colors = '#FF8A5B'
else:
colors = "#000000"
trace = go.Bar( y = [years],
x = [values],
orientation = 'h',
width = 0.5,
marker = {'color': colors},
)
if indicator == 'FitW.total.aggregate.score' or indicator == 'GII':
layout = go.Layout( title = title,
xaxis=dict(showgrid=False,
showline=True,
showticklabels=False,
zeroline=False,
tickfont=dict(family='Raleway',size=14),
range=[0,1] if indicator == 'GII' else [0,100]
),
yaxis=dict(showgrid=False,
showline=False,
showticklabels=False,
zeroline=False,
range= yrs_range
),
height = 150,
width=500,
margin=go.layout.Margin(
l=40,
#r=50,
#b=0,
t=0,
#pad=4
),
annotations=[
dict(
text="NO DATA AVAILABLE",
showarrow=False,
visible=True if (len(df_filtered) == 0) else False
),
dict(x=0.0,
y=-.85,
xref='x',
axref='x',
yref='paper',
ayref='pixel',
xanchor='left',
align='left',
text='Source: ' + df.loc[df['Name'] == indicator, 'Source'].tail(1).tolist()[0] + ' (' + str(int(
df.loc[df['Name'] == 'FotN', 'db_year'].tail(1).tolist()[0])) + ')<br>Technology & Social Change Group, University of Washington',
showarrow=False,
font=dict(family='Raleway',size=14)
),
dict(
text="More Equal (0)" if indicator == 'GII' else "Least free (0)",
x=0,
xanchor="left",
y=-0.00,
yanchor="top",
xref='x',
yref='paper',
showarrow=False,
font=dict(family='Raleway',size=13, color='blue')
),
dict(
text="Less Equal (1)" if indicator == 'GII' else "Most free (100)",
x=1 if indicator == 'GII' else 100,
xanchor="right",
y=-0.00,
yanchor="top",
xref='x',
yref='paper',
showarrow=False,
font=dict(family='Raleway',size=13,color='blue')
),]
)
else:
layout = go.Layout( title = title,
xaxis=dict(showgrid=False,
showline=True,
showticklabels=False,
zeroline=False,
tickfont=dict(family='Raleway',size=14),
range=[0,100]
),
yaxis=dict(showgrid=False,
showline=False,
showticklabels=False,
zeroline=False,
range= yrs_range
),
height = 150,
width=500,
margin=go.layout.Margin(
l=40,
#r=50,
#b=100,
t=0,
#pad=4
),
annotations=[
dict(
text="NO DATA AVAILABLE",
showarrow=False,
visible=True if (len(df_filtered) == 0) else False
),
dict(x=0.0,
y=-.85,
xref='x',
axref='x',
yref='paper',
ayref='pixel',
xanchor='left',
align='left',
text='Source: ' + df.loc[df['Name'] == indicator, 'Source'].tail(1).tolist()[0] + ' (' + str(int(
df.loc[df['Name'] == 'FotN', 'db_year'].tail(1).tolist()[0])) + ')<br>Technology & Social Change Group, University of Washington',
showarrow=False,
font=dict(family='Raleway',size=14)
),
dict(
text="Least free (0)",
x=0,
xanchor="left",
y=-0.00,
yanchor="top",
xref='x',
yref='paper',
showarrow=False,
font=dict(family='Raleway',size=13, color='blue')
),
dict(
text="Most free (100)",
x=100,
xanchor="right",
y=-0.00,
yanchor="top",
xref='x',
yref='paper',
showarrow=False,
font=dict(family='Raleway',size=13,color='blue')
),]
)
return go.Figure(data=[trace],layout=layout)
def generate_sparklines_bar_chart(selected_country, indicator, title, categories=None):
"""
generates a sparklines style (compact) bar chart for the selected country and indicator.
:param selected_country: selected country
:param indicator: name of indicator
:param title: title of the bar chart
:param categories: a list of dicts defining the "name", "range", and "color" of categorical variables.
EX: [{"name": "category 1", "range": [lower_bound, upper_bound], "color": "#0000FF"}, ... ]
:return: sparklines bar chart
"""
# filter data
df_filtered = df[df["Country"] == selected_country] # by selected country
df_filtered = df_filtered[df_filtered["Name"] == indicator] # by indicator
df_filtered = df_filtered.dropna(axis="index", subset=["value"]) # drop rows with missing indicator values
values = list(df_filtered["value"])
years = list(df_filtered["Year"])
trace = go.Bar(
x=years,
y=values,
)
layout = go.Layout(
annotations=[
dict(
text='Source: ' + df.loc[df['Name'] == indicator, 'Source'].tail(1).tolist()[0] + ' (' + str(int(
df.loc[df['Name'] == 'FotN', 'db_year'].tail(1).tolist()[0])) + ')<br>Technology & Social Change Group, University of Washington',
showarrow=False,
x=0.0,
y=-.65,
yref='paper',
xref='paper',
# axref='x',
font=dict(family='Raleway',size=14),
align='left',
),
dict(
text="NO DATA AVAILABLE",
showarrow=False,
visible=True if (len(df_filtered) == 0) else False
),
],
title={'text': title, 'xanchor': 'center', 'x':0.5,},
titlefont=dict(color=PLOT_COLORS["title"],family='Raleway',size=20),
height=275,
width=550,
showlegend = False,
margin=dict(
l=50,
r=50,
b=75,
t=80,
pad=10
),
xaxis=dict(
#tickmode="auto",
tickfont=dict(family='Raleway',size=14),
range=[2009.5,2020.5] if indicator == 'FitW.total.aggregate.score' else [2010.5,2020.5],
side="top"
),
yaxis=dict(
#tickmode="auto",
tickfont=dict(family='Raleway',size=14),
range=[1,0] if indicator == 'GII' else [100,0]
)
)
if categories is not None:
# create colorscale for bars
colorscale = []
for cat in categories:
colorscale.append([cat["range"][0] / (1 if indicator == 'GII' else 100), cat["color"]])
colorscale.append([cat["range"][1] / (1 if indicator == 'GII' else 100), cat["color"]])
trace["marker"]["cmin"] = categories[0]["range"][0] # set the minimum value of the colorbar
trace["marker"]["cmax"] = categories[-1]["range"][1] # set the maximum value of the colorbar
trace["marker"]["color"] = values # color bars based on bar height(value)
trace["marker"]["colorscale"] = colorscale # set colorscale
trace["marker"]["showscale"] = True if indicator != "GII" else False # display colorbar
trace["marker"]["colorbar"] = dict( # format colorbar
tickmode='array',
tickvals=[cat["range"][1] for cat in categories],
ticktext=[cat["name"] for cat in categories],
ticks='outside',
thickness = 20
)
# a figure combining data and layout
return go.Figure(data=[trace], layout=layout)
# ----- layout generation functions -----
def generate_country_profile(description):
"""
Generates country profile layout
:return: country profile layout
"""
return html.Div(
id='country-profile',
children=[
# ----- country profile title -----
html.H4('COUNTRY PROFILE'),
# ----- country profile sections -----
html.Div(
children=[
# ----- country population -----
html.Div(
className='country-profile-section',
children=[
html.Div(
children=[
# ----- title -----
html.Span(
className="title",
children='Population'
),
]
),
# ----- value -----
html.Div(
html.Span(
className="value",
id='country-population-value'),
)
]
),
# ----- country income group -----
html.Div(
className='country-profile-section',
children=[
html.Div(
children=[
# ----- title -----
html.Span(
className="title",
children='Income Group'
),
]
),
# ----- value -----
html.Div(
html.Span(
className="value",
id='country-income-group'),
)
]
),
# ----- UN sub region group -----
html.Div(
className='country-profile-section',
children=[
html.Div(
children=[
# ----- title -----
html.Span(
className="title",
children='UN Sub Region'
),
# ----- (optional) info icon -----
html.Img(
src='https://s3-us-west-2.amazonaws.com/da2i/Images/Info_Icon_Purple.png',title=', '.join(description)
)
]
),
# ----- value -----
html.Div(
html.Span(
className="value",
id='country-sub-region'),
)
]
)
]
)
]
)
def generate_quick_look_layout(dashboard, sections):
"""
This function generates a quick look layout with the number of sections specified by the sections parameter. Section ids are of
the form <dashboard>-quick-look-section-<section number>. Section numbers are indexed from 1.
:param dashboard: name of the dashboard for which the quick look layout is being generated
:param sections: the number of sections to be generated
:return: quick look layout
"""
quick_look = html.Div(
className='quick-look',
children=[
# ----- title -----
html.Div(
className='quick-look-title',
children=[
html.Span('QUICK LOOK'),
html.Img(
src='https://s3-us-west-2.amazonaws.com/da2i/Images/Spyglass_Icon.png',
),
],
)
])
section_divs = []
for i in range(sections):
temp_div = html.Div(
className='quick-look-section',
id='{}-quick-look-section-{}'.format(dashboard, i + 1)
)
section_divs.append(temp_div)
quick_look.children.extend(section_divs)
return quick_look
# ----- connectivity helper functions -----
# -- misc --
# TODO: Remove style from generateTable()
def generateConnectivityTable(indicator, rank, pct_change, selected_country, max_year, name, description):
"""
This function generates a Table component containing the passed values. It was originally named generateTable().
It is only used to generate tables in the connectivity dashboard.
:return: Table component
"""
return html.Table(
# Header
[html.Tr([html.Th('Indicator Name', style={'textAlign': 'left'}),
html.Th('', style={'padding': '0 0 0 18px', 'textAlign': 'left'}),
html.Th(selected_country, style={'padding': '0 0 0 8px', 'textAlign': 'right'}),
html.Th('Year', style={'padding': '0 0 0 8px', 'textAlign': 'right'}),
html.Th('% change', style={'padding': '0 0 0 8px', 'textAlign': 'right'})],
style={'borderTop': '1px solid light-grey', 'fontSize': '16px', 'color': 'grey'})] +
# Body
[html.Tr([html.Td(name,
style={'textAlign': 'left', 'fontSize': '16px'}),
html.Td(html.Div(html.Img(src='https://s3-us-west-2.amazonaws.com/da2i/Info_Icon_Purple.png',
style={'width': '20px', 'marginTop': '2px'}),
title=description),
style={'float': 'left'}),
html.Td(str(indicator),
style={'textAlign': 'right', 'fontSize': '16px'}),
# html.Td(str(indicator) + ' (' + str(max_year) + ')',
# style={'textAlign': 'right','fontSize':'16px'}),
# html.Td(str(rank),
# style={'textAlign': 'right','fontSize':'16px'}),
html.Td(str(max_year),
style={'textAlign': 'right', 'fontSize': '16px'}),
html.Td(str(pct_change),
style={'textAlign': 'right', 'fontSize': '16px'})],
style={'borderTop': '1px solid light-grey', 'border-bottom': '1px solid light-grey',
'color': '#38C0E1'}),
],
style={'width': '100%'}
)
def getCountryData(selected_country, indicator):
"""
This function filters data by selected_country and indicator and return NaN if none available.
:param selected_country: the country to filter by
:param indicator: indicator to filter by
:return: DataFrame filtered by selected_country
"""
filtered_df = df.loc[(df['Country'] == selected_country) & (df['Name'] == indicator) & (df['Year'] >= 2006)]
if (filtered_df.shape[0] == 0):
filtered_df['Year'] = range(2006, 2017)
filtered_df['value'] = np.nan
filtered_df['Country'] = selected_country
filtered_df['Name'] = indicator
return filtered_df
else:
return filtered_df
def getCountryRank(selected_country, region, indicator, ascending=True):
"""
This function computes the rank of selected_country within its region for the specified indicator. By default, a
country with a higher indicator value is assigned a higher rank. This behavior can be reversed by using
ascending=False.
:param selected_country: country for which to compute rank within region
:param region:
:return: rank
"""
# get latest years data for each country in region
rnk = df.loc[(df['Region'] == region) & (df['Name'] == indicator)]
rnk.sort_values(['Country', 'Year'], inplace=True)
rnk = rnk.groupby('Country').tail(1)
if ascending is True:
rnk.sort_values('value', ascending=False, inplace=True)
else:
rnk.sort_values('value', inplace=True)
rnk['ranks'] = range(1, rnk.shape[0] + 1)
return str(rnk.loc[rnk['Country'] == selected_country, 'ranks'].tolist()[0]) + ' of ' + str(rnk.shape[0])
def weightedAverage(region, indicator):
"""
Computes weighted average of indicator by population for the specified region and indicator.
:return: weighted average or NaN if no data exists
"""
rgl = df.loc[(df['Region'] == region) & (df['Name'] == indicator)]
## get population data and merge in
rgl = rgl.merge(df.loc[(df['Region'] == region) & (df['Name'] == 'population'), ['Country', 'Year', 'value']],
on=['Country', 'Year'],
how='left')
rgl['population'] = rgl.groupby('Country')['value_y'].ffill()
rgl['population'] = rgl.groupby('Country')['value_y'].bfill()
## compute weighted average by year
rgl['w_value'] = rgl['value_x'] * rgl['population']
result = rgl.groupby('Year', as_index=False).agg({'w_value': sum}).merge(rgl.groupby('Year', as_index=False).agg({'population': sum}))
result['w_avg'] = result['w_value'] / result['population']
return result[['Year', 'w_avg']]
# -- charts --
def generate_time_series_line_chart(selected_country, indicator, title, ylabel):
"""
This function generates a time series line chart showing the value of the selected indicator for the selected
country and its region over time.
:param selected_country: selected country from dropdown
:param indicator: indicator for which to plot data
:param title: title of the plot
:param ylabel: label of the y axis
:return: time series line chart
"""
# Create and style traces
filtered_df = getCountryData(selected_country, indicator=indicator)
# Compute regional average weighted by country population
rgn = df.loc[df.Country == selected_country, 'Region'].tolist()[0]
regional = weightedAverage(rgn, indicator=indicator)
maxValue = max([filtered_df['value'].max(), regional['w_avg'].max()]) if len(filtered_df) != 0 else 'NA'
sourceText = 'Source: ' + df.loc[df['Name'] == indicator, 'Source'].tail(1).tolist()[0] + ' (' + str(int(df.loc[df['Name'] == indicator, 'db_year'].tail(1).tolist()[0])) + ')<br>Technology & Social Change Group, University of Washington'
return {
'data': [
go.Scatter( # Country data
x=filtered_df['Year'],
y=filtered_df['value'],
text=filtered_df['Country'],
name=filtered_df['Country'].tolist()[0],
line=dict(
color=(PLOT_COLORS["country"]),
width=4),
marker=dict(
size=MARKER_SIZE
)
),
go.Scatter( # Regional average
x=regional['Year'],
y=regional['w_avg'],
text=rgn,
name=rgn,
line=dict(
color=(PLOT_COLORS["region"]),
width=4),
marker=dict(
size=MARKER_SIZE
)
)
],
## Edit the layout
'layout': go.Layout(
title=title, titlefont=dict(size=20, color=PLOT_COLORS["title"], family='Raleway'),
font=dict(family='Raleway', size=13),
xaxis=dict(title='',
range=[2005.5, 2018.5] if indicator != 'ind.internet' else [2005.5,2018.5], # NOTE: Should this range be dynamic?
tick0=2006,
dtick=2),
yaxis=dict(title=ylabel,
range=[0, 100]), #if maxValue < 100 else int(math.ceil(maxValue / 50.0)) * 50] if maxValue != 'NA' else [0,100]),
legend=dict(x=.1,
y=1 if filtered_df['value'].tolist()[0] < 40 else 0.1),
height=PLOT_HEIGHT,
width=500,
# paper_bgcolor='#FCFCFC', # set figure background color
# plot_bgcolor='#CCC', # set plot area background color
annotations=[dict(text="NO DATA AVAILABLE",
showarrow=False,
visible=True if (len(filtered_df) == 0) else False
),
dict(
x=2005.5,
y=-.35,
xref='x',
axref='x',
yref='paper',
ayref='pixel',
xanchor='left',
align='left',
text=sourceText,
showarrow=False,
font=dict(family='Raleway')
)
]
)
}
def generate_internet_user_gender_gap_chart(selected_country):
"""
This function generates the "internet user gender gap" chart on the connectivity dashboard.
:param selected_country: selected country from dropdown
:return: internet user gender gap chart
"""
## Create and style traces
filtered_df = df.loc[(df.Country == selected_country) & \
(df['Name'].isin(['ind.internet.female', 'ind.internet.male',
'Pct.internet.All.Rural', 'Pct.internet.All.Urban']))]
filtered_df.sort_values('Year', inplace=True)
## safely pull data, planning for lots of missing
x1 = [filtered_df.loc[filtered_df['Name'] == 'ind.internet.male', 'value'].tail(1).tolist()[0] if (filtered_df.shape[
0] > 0) & (
'ind.internet.male' in
filtered_df[
'Name'].unique()) else np.nan,
filtered_df.loc[filtered_df['Name'] == 'ind.internet.female', 'value'].tail(1).tolist()[0] if (filtered_df.shape[
0] > 0) & (
'ind.internet.female' in
filtered_df[
'Name'].unique()) else np.nan]
x2 = [
filtered_df.loc[filtered_df['Name'] == 'Pct.internet.All.Rural', 'value'].tail(1).tolist()[0] if (filtered_df.shape[
0] > 0) & (
'Pct.internet.All.Rural' in
filtered_df[
'Name'].unique()) else np.nan,
filtered_df.loc[filtered_df['Name'] == 'Pct.internet.All.Urban', 'value'].tail(1).tolist()[0] if (filtered_df.shape[
0] > 0) & (
'Pct.internet.All.Urban' in
filtered_df[
'Name'].unique()) else np.nan]
# Create the graph with subplots
trace1 = go.Bar(
x=x1,
y=['Men ', 'Women '],
orientation='h',
opacity=0.6,
textposition='auto',
name='Internet use by gender',
width=0.8,
marker=dict(
color=[PLOT_COLORS["men"], PLOT_COLORS["women"]],
line=dict(
color='rgb(8,48,107)',
width=0.3,
)
)
)
trace2 = go.Bar(
x=x2,
y=['Rural ', 'Urban '],
orientation='h',
opacity=0.6,
textposition='auto',
name='Internet use by urban/rural',
width=0.8,
marker=dict(
color=[PLOT_COLORS["rural"], PLOT_COLORS["urban"]],
line=dict(
color='rgb(8,48,107)',
width=0.3,
)
)
)
src_text = 'Source: International Telecommunication Union (2019)<br>Technology & Social Change Group, University of Washington'
fig = tools.make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.25,subplot_titles=())
fig.append_trace(trace1, 1, 1)
fig.append_trace(trace2, 2, 1)
fig['layout'].update(height=400,width=500)
fig['layout']['xaxis1'].update(range=[0, 100],tickfont=dict(family='Raleway',size=12))
fig['layout']['yaxis1'].update(tickfont=dict(family='Raleway',size=12),linewidth=0)
fig['layout'].update(showlegend=False, title='Who is using the internet?')
fig['layout'].update(font=dict(size=20, family='Raleway'))
fig['layout']['yaxis2'].update(tickfont=dict(family='Raleway',size=12))
fig['layout']['title'].update(font=dict(family='Raleway',size=20,color=PLOT_COLORS["title"]))
fig.update_xaxes(range=[0, 100])
if (sum(np.isnan(x1)) < 2) & (sum(np.isnan(x2)) < 2):
fig['layout'].update(annotations=[
dict(x=0.5, y=-.35, xref='x', axref='x', yref='paper', ayref='pixel', xanchor='left', align='left', text=src_text,
showarrow=False, font=dict(family='Raleway',size=12))])
elif (sum(np.isnan(x1)) == 2) & (sum(np.isnan(x2)) == 0):
fig['layout'].update(annotations=[
dict(x=0.5, y=-.35, xref='x', axref='x', yref='paper', ayref='pixel', xanchor='left', align='left', text=src_text,
showarrow=False, font=dict(family='Raleway',size=12)),
dict(x=20, y=.83, xref='x', axref='x', yref='paper', ayref='pixel', xanchor='left',
text='NO DATA AVAILABLE', showarrow=False,font=dict(family='Raleway',size=8))])
elif (sum(np.isnan(x1)) == 0) & (sum(np.isnan(x2)) == 2):
fig['layout'].update(annotations=[
dict(x=0.5, y=-.35, xref='x', axref='x', yref='paper', ayref='pixel', xanchor='left', align='left', text=src_text,
showarrow=False, font=dict(family='Raleway',size=12)),
dict(x=20, y=.17, xref='x', axref='x', yref='paper', ayref='pixel', xanchor='left',
text='NO DATA AVAILABLE', showarrow=False, font=dict(family='Raleway',size=12))])
else:
fig['layout'].update(annotations=[
dict(x=0.5, y=-.35, xref='x', axref='x', yref='paper', ayref='pixel', xanchor='left', align='left', text=src_text,
showarrow=False, font=dict(family='Raleway',size=12)),
dict(x=20, y=.17, xref='x', axref='x', yref='paper', ayref='pixel', xanchor='left',
text='NO DATA AVAILABLE', showarrow=False, font=dict(family='Raleway')),
dict(x=20, y=.83, xref='x', axref='x', yref='paper', ayref='pixel', xanchor='left',
text='NO DATA AVAILABLE', showarrow=False, font=dict(family='Raleway'))])
return fig
def generate_mobile_broadband_cost_pie_chart(selected_country):
pcolors = ['#ff8a5b', '#38C0E1']
cost = df.loc[(df.Country == selected_country) & (df.Name == 'mobile.broadband.cost')]
cost.sort_values('Year', inplace=True)
if len(cost) != 0:
cost = round(cost['value'].iloc[-1], 2)
gni = 100 - cost if cost < 100 else 0
else:
cost = 'NA'
gni = 'NA'
if cost != 'NA':
return {'data': [go.Pie(labels=["Monthly income spent on Mobile Broadband", "Proportion of remaining income"],
values=[cost, gni],
hoverinfo='label+percent',
textinfo='none',
textfont=dict(size=14,family='Raleway'),
marker=dict(colors=pcolors,
line=dict(color='#000000', width=0)), hole=.7, pull=[0.1, 0])],
'layout': {'fill': '#ff8a5b',
'title': 'What percent of a person’s monthly income <br> is needed to pay for mobile broadband services?',
'titlefont': {'size': '20', 'color': PLOT_COLORS["title"], 'family': 'Raleway'},
"height": "450",
"legend": {"x": "14","y":"-0.15"},
"width": "500",
"font": {"size": "14","family":"Raleway"},
"insidetextfont":{"size":"12","family":"Raleway"},
# "margin": {"b" : "500"},
"annotations": [
{
"showarrow": False,
"font": {"family":"Raleway"},
"align": "left",
"text": 'Source: ' +
str(df.loc[df['Name'] == 'mobile.broadband.cost', 'Source'].tail(1).tolist()[
0]) + ' (' + str(int(df.loc[df['Name'] == 'mobile.broadband.cost', 'db_year'].tail(1).tolist()[0])) + ')<br>Technology & Social Change Group, University of Washington',
"x": 0.00,
"y": -0.3
}
]}
}
else:
return {'data': [go.Pie(labels=["Monthly income spent on Mobile Broadband", "Proportion of remaining income"],
values=[0,0],
hoverinfo='label+percent',
textinfo='none',
textfont=dict(size=14,family='Raleway'),
marker=dict(colors=pcolors,
line=dict(color='#000000', width=0)), hole=.7, pull=[0.1, 0])],
'layout': {'fill': '#ff8a5b',
'title': 'What percent of a person’s monthly income is needed to pay <br>for mobile broadband services?',
'titlefont': {'size': '20', 'color': PLOT_COLORS["title"], 'family': 'Raleway'},
"height": "450",
"legend": {"x": "14","y":"-0.15"},
"width": "650",
"font": {"size": "14","family":"Raleway"},
"insidetextfont":{"size":"12","family":"Raleway"},
"annotations": [
{
"showarrow": False,
"font": {"family":"Raleway","size":"16"},
"text": 'NO DATA AVAILABLE',
"visible": True if cost == 'NA' else False,
"x": 0.5,
"y": 0.5
},
{
"showarrow": False,
"font": {"family":"Raleway"},
"text": 'Source: International Telecommunication Union (2019)<br>Technology & Social Change Group, University of Washington',
"x": 0.00,
"y": -0.3
}
]}
}
# -- tables --
def generate_most_recent_value_table(selected_country, indicator, indicator_name, format_as_rate=False):
"""
Generates tables for all but "internet user gender gap" table on the connectivity dashboard.
:param selected_country: selected country from dropdown
:param indicator: indicator for which to generate table
:param indicator_name: Name of the indicator to display in table
:param format_as_rate: boolean to format as <value>/100 instead of as percent
:return: most recent value table
"""
# Filter data by selected_country and indicator, then sort by year
ind_internet = df.loc[(df.Country == selected_country) & (df.Name == indicator)]
ind_internet.sort_values('Year', inplace=True)
if (len(ind_internet) == 0):
return ""
# find most recent year for which there is data
max_year = ind_internet['Year'].tail(1).tolist()[0] if len(ind_internet) != 0 else 'NA'
# get region of selected_country
region = df.loc[df.Country == selected_country, 'Region'].tolist()[0] if len(ind_internet) != 0 else 'NA'
# compute percent change
val1 = ind_internet['value'].tail(1).tolist()[0] if len(ind_internet) != 0 else 'NA'
val2 = ind_internet['value'].tail(2).head(1).tolist()[0] if len(ind_internet) != 0 else 'NA'
if indicator == 'GII':
pctChange = round(val1 - val2, 3) if len(ind_internet) != 0 else 'NA'
# pctChange = round(((val1 - val2) / val2) * 100, 3) if len(ind_internet) != 0 else 'NA'
else:
pctChange = int(round(((val1 - val2) / val2) * 100, )) if len(ind_internet) != 0 else 'NA'
if pctChange == 'NA':
pctChange = pctChange
elif pctChange > 0:
if indicator == 'GII':
pctChange = '▲ ' + str(abs(pctChange))
else:
pctChange = '▲ ' + str(abs(pctChange)) + '%'
elif pctChange < 0:
if indicator == 'GII':
pctChange = '▼ ' + str(abs(pctChange))
else:
pctChange = '▼ ' + str(abs(pctChange)) + '%'
else:
pctChange = str(pctChange) + '%'
# create description string
description = str(df.loc[df['Name'] == indicator, 'Long.name'].tail(1).tolist()[0]) \
+ '\n\n' \
+ str(df.loc[df['Name'] == indicator,'Description'].tail(1).tolist()[0]) \
+ '\n\nSource: ' + str(df.loc[df['Name'] == indicator, 'Source'].tail(1).tolist()[0]) \
+ ' (' + str(int(df.loc[df['Name'] == indicator, 'db_year'].tail(1).tolist()[0])) + ')'
if indicator == 'GII':