forked from gizdatalab/vulnerability_report
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
738 lines (519 loc) · 30.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
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
import streamlit as st
import pandas as pd
import plotly
import plotly.express as px
import matplotlib.pyplot as plt
from datetime import datetime
import seaborn as sns
from matplotlib.dates import YearLocator, DateFormatter
from math import pi
import pyxlsb
########################## SET UP #####################################
st.set_page_config(layout="wide")
# Load data
df = pd.read_excel('data/vul_africa_01.xlsb', engine='pyxlsb')
# Define column name groups
non_target_columns=['Women and other genders',
'Sexual minorities (LGBTQI+)',
'Children',
'Older persons',
'Ethnic, racial or other minorities',
'Members of indigenous and local communities',
'Migrants and displaced persons',
'Persons living in poverty',
'Informal sector workers',
'Fishery communities',
'Agricultural communities',
'Persons with disabilities',
'Persons with pre-existing health conditions',
'Residents of drought-prone regions',
'Rural populations',
'Urban populations',
'Coastal communities']
target_columns = [col for col in df.columns if 'T_' in col]
summary_columns = [col for col in df.columns if 'sum_' in col]
categories_high_level = ['Gender',
'Age',
'Socio-economic',
'Occupation',
'Health',
'Geographic']
categories_high_level_target = [col for col in df.columns if 't_' in col]
###################### Process data ############################
# We create a cleaned version of the original dataframe and drop all countries that don't have entries yet
# We add columns for each group that counts the overall score of both non-target and target references
df_cleaned = df[['Country', 'code3', 'year'] + categories_high_level + categories_high_level_target + target_columns + non_target_columns + summary_columns].dropna()
# Sum up count for non_target and target for each group
for group in non_target_columns:
df_cleaned[f'All_g_{group}'] = df_cleaned[group] + df_cleaned[f'T_{group}']
all_count_group_columns = [col for col in df_cleaned.columns if 'All_g_' in col]
# Sum up count for non_target and target for each category
for category in categories_high_level:
df_cleaned[f'All_c_{category}'] = df_cleaned[category] + df_cleaned[f't_{category}']
all_count_category_columns = [col for col in df_cleaned.columns if 'All_c_' in col]
####################### Header ##################################
st.image('images/header3.png', caption=None, width=None, use_column_width=None, clamp=False, channels="RGB", output_format="auto")
st.subheader("")
st.subheader("""Are you interested in how different groups are represented in country's climate policy? Then this is the report for you. Using AI, we analysed the climate policy documents (NDCs) of different countries to show how often certain groups are being referenced and provide an overview of the concrete policy actions and targets for each group.""")
st.divider()
####################### Background and Methodology ##################################
st.header("1. Background and Methodology")
st.header("")
col1,col2,col3=st.columns([1,0.1,1])
with col1:
st.write("""The consequences of the climate crisis are affecting people across the world. Still, it
is well-known that people in vulnerable situations (due to factors including but not
limited to age, gender, geography, health or indigenous or minority status) are disproportionately
more affected than other demographic groups.""")
st.write("""When signing the 2015 Paris Agreement, countries
committed to taking this differential exposure into account and considering groups in vulnerable
situations when integrating
adaptation into relevant socioeconomic and environmental policies and actions, where appropriate
(Article 7.5). These considerations are commonly mirrored in governments’ climate policy documents
such as the Nationally Determined Contributions (NDCs). However, while the information is out
there, it proves difficult gaining a complete understanding to what extent different groups are
considered in each country’s climate policy since manually going through the documents and
identifying references to different groups can be time- and resource-intensive.""")
st.write("""To address this knowledge gap, we came up with a use case using AI and natural language
processing (NLP) techniques to allow for a systematic
review of references and tangible actions related to groups in vulnerable situations
in climate policy documents. The use case was initiated together with our colleagues from the
NDC Assist programme of GIZ Kenya and the CRAWN Trust and implemented together with support from GFA.""")
with col3:
st.image('images/GIZ_Foto_smaller.png', caption=None, width=None, use_column_width=None, clamp=False, channels="RGB", output_format="auto")
st.header("")
st.divider()
############## How can AI help? #################
st.subheader("What is the role of AI?")
col1,col2,col3=st.columns([1,0.1,1])
with col1:
st.write("""In our efforts to analyze climate policy documents, such as Nationally Determined
Contributions (NDCs), we've turned to the power of Artificial Intelligence (AI) to help
us navigate through vast amounts of text efficiently. AI plays a crucial role by enabling
us to sift through these documents and identify references to various vulnerable groups
with speed and accuracy. By using Natural Language Processing (NLP) techniques, we can train a
language model to understand the context and meaning of the text, allowing us to categorize mentions of
vulnerable groups effectively. Text classification, a key component of NLP, works by teaching the model to
recognize patterns in the text and assign labels accordingly. This
process helps us to extract valuable insights from the documents, ultimately aiding
policymakers and researchers in better understanding how climate policies address the
needs of vulnerable populations.""")
st.write("""For the model to learn, it needs to be trained on example
paragraphs of similiar text. Click yourself through the tabs on the right to get more information
on the process and the technical background.""")
with col3:
st.info("Explore the technical process by clicking yourself through the tabs below.")
tab1, tab2, tab3, tab4 = st.tabs(["Data Collection", "Training", "Active Learning", "Results"])
# Data Collection
with tab1:
col1,col2,col3=st.columns([1,0.1,1])
with col3:
st.write("""For the AI to learn the context of the different groups, it needs to be fine-tuned with training data,
so it can learn the patterns and contexts to search for. The first round of training data has been collected
manually by a team of four colleagues. We collected ten paragraphs per group that resemble the information
that we would like the AI to identify for the group. The training paragraphs were taken from climate policy
or similar documents.""")
with col1:
st.image('images/data_collection_icon.png', caption=None, width=None, use_column_width=None, clamp=False, channels="RGB", output_format="auto")
# Training
with tab2:
col1,col2,col3=st.columns([1,0.1,1])
with col3:
st.write("""We then used the collected training data for a first round of training. To not start from scratch,
we fine-tuned an already pre-trained AI model that has a general understanding of language. By providing it with
our training data, it learns to specifically look for references to the different groups. For the training of the
model, we used a framework called "SetFit" which has the benefit that you only need few data points for each group.""")
with col1:
st.image('images/training1_icon.png', caption=None, width=None, use_column_width=None, clamp=False, channels="RGB", output_format="auto")
# Active Learning
with tab3:
col1,col2,col3=st.columns([1,0.1,1])
with col3:
st.write("""To increase the performance of the model, the dataset has later been extended to at least 20 examples
per group. To avoid the time-consuming process of having to collect the paragraphs manually again, we relied on “active learning”,
meaning we used the first version of the fine-tuned model to predict whether paragraphs from climate
documents reference different groups and then went through the results and annotated whether the predictions are wrong or right.""")
with col1:
st.image('images/training2_icon.png', caption=None, width=None, use_column_width=None, clamp=False, channels="RGB", output_format="auto")
# Results
with tab4:
col1,col2,col3=st.columns([1,0.1,1])
with col3:
st.write("""Once the model learned to recognize the context related to each group, we used it to analyse the NDCs of different English-speaking
African countries. Each NDC has been split in paragraphs of length of approximately 60 words. The AI then predicts whether the paragraph
contains a reference to one or multiple groups and a second model predicts whether the reference is specific (i.e., referencing a
concrete action or target) or if it is a more general mention of the group.""")
with col1:
st.image('images/result_icon.png', caption=None, width=None, use_column_width=None, clamp=False, channels="RGB", output_format="auto")
""
st.header("")
############## Climate Policy Documents #################
st.subheader("Climate Policy Documents")
col1,col2,col3= st.columns([1,0.1,1])
with col3:
st.write("""National Determined Contributions (NDCs) are documents outlining
a country's climate action plan, a crucial component of the global
effort to address climate change. The decision for governments to
publish NDCs was a key outcome of the 2015 Paris Agreement, where
nations collectively committed to limiting global warming to well
below 2 degrees Celsius above pre-industrial levels. NDCs serve
as a tangible expression of a country's commitment to reducing
greenhouse gas emissions and adapting to the impacts of climate change.
Initially submitted in 2015, NDCs are expected to be updated every five
years to reflect evolving circumstances, technology advancements, and
the need for more ambitious targets. These documents typically encompass
mitigation goals, adaptation strategies, and details on financial and
technical support required for implementation. Regular updates and
transparency in reporting play a crucial role in tracking progress and
fostering international collaboration to achieve the overarching climate
objectives set forth in the Paris Agreement.""")
with col1:
fig, ax = plt.subplots(1, 1)
# Get plot data
df_dates = df_cleaned[['Country', 'year']].dropna()
df_dates['year'] = df_dates['year'].apply(lambda x: datetime(int(x), 1, 1))
df_dates['year'] = df_dates['year'].apply(lambda x: x.date())
##### Graph ######
# Create colour palette
unique_years = sorted(df_cleaned['year'].unique())
color_palette = sns.color_palette("flare", n_colors=len(unique_years))
year_color_dict = dict(zip(unique_years, color_palette))
# Stile ticks
fig.autofmt_xdate()
fig.set_size_inches(18, 10)
# Hide y and x axis
ax.yaxis.set_visible(False)
ax.get_yaxis().set_ticklabels([])
#Hide spines
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.xaxis.set_ticks_position('bottom')
#Leave left/right marging on x-axis
min_date = df_dates['year'].min()
max_date = df_dates['year'].max()
month_offset = pd.DateOffset(months=12)
ax.set_xlim(min_date, max_date)
ax.set_xlim(min_date - month_offset, max_date + month_offset)
# Adjust x-axis labels
years = YearLocator()
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(DateFormatter('%Y'))
ax.tick_params(axis='x', labelsize=18, rotation=0, pad=15)
ax.xaxis.set_ticks_position('none')
ax.spines['bottom'].set_visible(False)
ax.get_xticklabels()[0].set_visible(False)
# Create country time lines
height_of_line = 0
for country in df_dates['Country'].unique():
ax.axhline(
height_of_line,
linewidth=1,
color='#CCCCCC')
ax.annotate(
country,
(min_date - month_offset, height_of_line),
fontsize=15)
height_of_line += 1
# Add dots
ax.scatter(
x = df_dates['year'].tolist(),
y = df_dates['Country'].tolist(),
s = 1000, # dot size
c='#8338ec',
marker='o',
linewidth=1,
alpha=0.5)
#fig.set_size_inches(18, 4)
fig
# Caption the graph
st.caption("Graph 1 - When did each country publish their NDCs?")
st.header("")
############## Which groups are being considered? #################
st.subheader("Which groups are being considered in the analysis?")
st.subheader("")
col1,col2,col3= st.columns([1 ,0.1, 1])
with col3:
st.image('images/framework.png', caption=None, width=None, use_column_width=None, clamp=False, channels="RGB", output_format="auto")
with col1:
st.write("""In our pursuit to understand climate vulnerability, we initially focused on women,
children, and youth. Recognizing the need for a broader perspective, we shifted towards
an intersectional approach but found no existing taxonomy that matched our comprehensive
vision. Therefore, we drew on insights from the sector-program on human rights and our
policy analysis experience to create a new taxonomy.""")
st.write("""This framework incorporates gender, age, socio-economic status, occupation, health, and geographical
factors to capture the nuanced ways these elements interact and influence vulnerability to
climate change. This intersectional taxonomy is important to our project, enhancing our understanding
of the complex challenges diverse groups face due to climate change. The graphic shows which groups
have been considered in our analysis.""")
st.header("")
############## Do the references contain a specific measure or target? #################
st.subheader("Do the references contain a specific measure or target?")
col1,col2,col3= st.columns([1,0.1,1])
with col1:
st.write("""To make predictions on whether a certain paragraph includes a reference
to one of the vulnerable groups mentioned above, we have created our own
training dataset to fine-tune a pre-trained sentence transformer model
(i.e., deep learning model designed for encoding and transforming sentences
or text paragraphs into fixed-dimensional vectors).""")
with st.container():
st.write("This is considered a general reference to a group:")
st.caption("""Increased intensities and magnitudes of climate related risks in Kenya
aggravate conflicts, mostly over natural resources. This has frequently
forced the country to reallocate development resources to address
climate related emergencies. These impacts are not gender neutral,
impacting men, women and other gender groups differently.""")
with st.container():
st.write("This is considered an action reference to a group:")
st.caption("""P36: Conduct a climate risk and vulnerability assessment of the tourism
sector P37: Develop climate resilient action plans for the sector Gender, youth
and P38: Develop social safety net structures for women, youth and other
vulnerable groups within the CCCFs P39: Strengthen access of women, youth,
other vulnerable groups to enterprise funds, climate finance other vulnerable
groups""")
with col3:
st.info("Test your knowledge! Can you spot the difference between a general and a specific reference?")
# Retrieve data for quiz
df_target_quiz = pd.read_excel('data/target_quiz.xlsx')
# Check answer
def check_answer(option_chosen, other_answer, random_row_chosen):
# Code answer
if option_chosen == 'general':
answer = 'NO'
else:
answer = 'YES'
# Retrieve result
result = random_row_chosen['target'].iloc[0]
# Check answer
if answer == result:
return "You are correct!"
else:
return f"Sorry, but it is a {other_answer} reference."
# Define function to retrieve question
def get_quiz_question():
# Retrieve a random row
if 'quiz' not in st.session_state:
st.session_state.quiz = df_target_quiz.sample(n=1)
# Display info
st.write(f"This is a reference to {st.session_state.quiz['label'].iloc[0]}")
st.caption(st.session_state.quiz['text'].iloc[0])
st.write("What do you think? Choose one of the options below.")
# Answer options
col1, col2, col3= st.columns([1,1,1])
with col1:
if st.button("It's a general reference."):
with col1:
st.write(check_answer('general', 'target', st.session_state.quiz))
with col2:
if st.button("It's a target or action!"):
with col1:
st.write(check_answer('target', 'general', st.session_state.quiz))
# Option to restart
with col3:
if st.button("Get a new example", type="primary"):
del st.session_state.quiz
st.session_state.quiz = df_target_quiz.sample(n=1)
st.experimental_rerun()
return
# Initiate quiz
get_quiz_question()
# if st.button('Say hello'):
# st.write('Why hello there')
st.header("")
############# 2. What are the insights? ######################
st.divider()
st.header("2. What are our insights?")
############## What does each country focus on? ###############
st.subheader("What is each country's focus?")
# Get data for focus map high level * both target and non target *
df_high_level_counts_all= df_cleaned[['Country', 'code3'] + all_count_category_columns]
df_melted_high_level_all = df_high_level_counts_all.melt(id_vars=['Country', 'code3'], value_name='Count').rename(columns={"variable": "group"})
df_sorted_high_level_all = df_melted_high_level_all.sort_values(['code3', 'Count'], ascending=[True, False], ignore_index=True)
df_focus_high_level_all = df_sorted_high_level_all.groupby('Country').head(1)
df_focus_high_level_all['group'] = df_focus_high_level_all['group'].apply(lambda x: x.replace("All_c_", ""))
# Get data for focus map high level * Only target *
df_high_level_counts_target = df_cleaned[['Country', 'code3'] + categories_high_level_target]
df_melted_high_level_target = df_high_level_counts_target.melt(id_vars=['Country', 'code3'], value_name='Count').rename(columns={"variable": "group"})
df_sorted_high_level_target = df_melted_high_level_target.sort_values(['code3', 'Count'], ascending=[True, False], ignore_index=True)
df_focus_high_level_target = df_sorted_high_level_target.groupby('Country').head(1)
df_focus_high_level_target['group'] = df_focus_high_level_target['group'].apply(lambda x: x.replace("t_", ""))
# Define color palette * High level *
color_dict_high = {'Gender': '#E7AA7B',
'Age': '#D4585A',
'Socio-economic': '#C24462' ,
'Occupation': '#7B2F71' ,
'Health': '#4F2465' ,
'Geographic': '#AA3A6C' }
# Define color palette * Detailed level *
# color_list_detailed = ["#033270", "#1368aa", "#4091c9", "#9dcee2",
# "#fedfd4", "#f29479", "#f26a4f", "#ef3c2d",
# "#cb1b16", "#65010c", "#006466", "#219ebc",
# "#ffb703", "#fb8500", "#722e9a", "#5d2689",
# "#a24ccd"]
# color_dict_detailed = {key: value for key, value in zip(all_count_columns, color_list_detailed)}
# Create a function to display the focus map
def focus_map(data_input, color_dict_input):
"""The function takes a dataframe with three a "Country", "group" and "Count" column as an input,
as well as color definitions for each group. It outputs a world map of Africa displaying the
group of the highest count for each country."""
fig = px.choropleth(data_input,
scope = 'africa',
color="group",
locations="code3",
hover_data=["Country", "group"],
color_discrete_map=color_dict_input,
template = 'plotly',
)
# Remove the colourbar and legend
fig.update_layout(coloraxis_showscale=False)
fig.update_traces(showlegend=False)
# Adjust the left margin
fig.update_layout(margin=dict(l=0, r=0, b=0, t=0, pad=0))
# Update the layout to increase the size
fig.update_layout(
width=600, # Set the width of the plot
height=600, # Set the height of the plot
)
fig
return
### View ####
# Add toggle for people to choose a level of detail - high vs low
col1,col2,col3= st.columns([1,0.1,1])
with col1:
st.write("""National Determined Contributions (NDCs) are like a country's climate action
blueprint. These documents outline how each nation plans to tackle climate change
and reduce greenhouse gas emissions. What's interesting is that governments often
highlight different vulnerable groups in their NDCs, like women, children, and others.""")
st.write("""It's a bit like a customized approach to climate action. Different countries prioritize
different groups based on their unique circumstances. Some might focus on protecting
vulnerable ecosystems, while others emphasize safeguarding the well-being of specific
communities.""")
st.write("""What we're trying to do is offer insights into these variations. By understanding
how different countries prioritize and address the needs of specific vulnerable
groups, we can learn more about their unique challenges and tailor support accordingly.
It's not a one-size-fits-all solution; it's about recognizing diversity in approaches
to create a more inclusive and effective global response to climate change.""")
st.header("")
st.image('images/categories.png', caption=None, width=500, use_column_width=True, clamp=False, channels="RGB", output_format="auto")
st.header("")
focus_switch = st.toggle('Click here to change between all references and only target references')
with col3:
# If toggle not activated -> High level and All references
if not focus_switch:
st.subheader("Country focus for for all references:")
focus_map(df_focus_high_level_all, color_dict_high)
# If toggle activated -> High level and TARGET references
if focus_switch:
st.subheader("Country focus for for target and measures:")
focus_map(df_focus_high_level_target, color_dict_high)
############## 3. Country Deep Dive ############
st.divider()
st.image('images/country_deep_dive.png', caption=None, width=500, use_column_width=True, clamp=False, channels="RGB", output_format="auto")
st.header("3. Country Deep Dive")
st.subheader("Explore how your country of interest is including different groups in their climate policy plans.")
# Get the count for each group for all countries and sort by highest value
# Non-target counts
df_non_target_focus = df_cleaned[['Country', 'code3'] + non_target_columns].dropna()
df_melted_nontarget = df_non_target_focus.melt(id_vars=['Country', 'code3'], value_name='Count').rename(columns={"variable": "group"})
df_sorted_nontarget = df_melted_nontarget.sort_values(['code3', 'Count'], ascending=[True, False], ignore_index=True)
# Target counts
df_target_focus = df_cleaned[['Country', 'code3'] + target_columns].dropna()
df_melted_target = df_target_focus.melt(id_vars=['Country', 'code3'], value_name='Count').rename(columns={"variable": "group"})
df_sorted_target = df_melted_target.sort_values(['code3', 'Count'], ascending=[True, False], ignore_index=True)
## View ##
# Create selectbox
selected_country = st.selectbox("Please select a country", (df_cleaned.Country.unique()))
# Create columns
col1,col2,col3= st.columns([1,0.1,1])
with col1:
# Filter the data for the respective country and drop all categories that have no reference
country_table_nontarget = df_sorted_nontarget[df_sorted_nontarget['Country'] == selected_country].reset_index().drop(columns={"index", "code3"})
country_table_nontarget['Count'] = country_table_nontarget['Count'].apply(lambda x: int(x))
country_table_target = df_sorted_target[df_sorted_target['Country'] == selected_country].reset_index().drop(columns={"index", "code3"})
country_table_target['Count'] = country_table_target['Count'].apply(lambda x: int(x))
country_table_target['group'] = country_table_target['group'].apply(lambda x: x.replace("T_", "")
)
# Merge both
df_countries_count = country_table_nontarget.merge(country_table_target, on=['Country', 'group'], how="inner")
df_countries_count.rename(columns={'Count_x': 'General references', 'Count_y': 'Action or target references'}, inplace=True)
df_countries_count = df_countries_count[(df_countries_count['General references'] != 0) | (df_countries_count['Action or target references'] != 0)]
df_countries_count['All references'] = df_countries_count['General references'] + df_countries_count['Action or target references']
# Legend
st.image('images/legend_radar.png', caption=None, width=500, use_column_width=True, clamp=False, channels="RGB", output_format="auto")
# SPIDER GRAPH
def create_spider_graph(data_input_1, data_input_2, r_input_1, r_input_2):
# Create plot
fig = px.line_polar(data_input_1,
r=r_input_1,
theta='group',
line_close=True,
color_discrete_sequence=['blue']
)
# Add a second layer
fig.add_trace(px.line_polar(data_input_2,
r=r_input_2,
theta='group',
line_close=True,
color_discrete_sequence=['red']).data[0])
fig.update_traces(fill='toself')
fig
return
create_spider_graph(df_countries_count[['group', 'All references']],
df_countries_count[['group', 'Action or target references']] ,
'All references',
'Action or target references')
with col3:
# Display table
st.table(df_countries_count.drop(columns={'Country', 'General references'}))
### Get summary data
# Retrieve country summaries
df_summary = df[df["Country"] == selected_country]
summary_columns = [col for col in df_summary.columns if 'sum_' in col]
df_summary = df_summary[df_summary.columns.intersection(summary_columns)]
# Create dict with summaries for country
summaries_dict = {}
for row, col in df_summary.items():
if isinstance(col.iloc[0], str):
if len(col.iloc[0]) > 5:
# Retrieve group name
group_name = col.name.replace("sum_", "")
# Retrieve summary
summary = col.iloc[0]
# Format summary
bullet_points = summary.split("•")
# Remove any leading or trailing whitespace from each bullet point
formatted_bullet_points = [point.strip() for point in bullet_points if point.strip()]
# Join the bullet points with Markdown bullet point syntax
formatted_string = "\n".join(f"- {point}" for point in formatted_bullet_points)
# Attach
summaries_dict[group_name] = formatted_string
# Display summary data
for key, value in summaries_dict.items():
st.write(key)
st.caption(value)
############## 4. Country Comparison ############
# st.divider()
# #st.image('images/country_deep_dive.png', caption=None, width=500, use_column_width=True, clamp=False, channels="RGB", output_format="auto")
# st.header("4. Country Comparison")
# st.subheader("Explore how your country of interest is including different groups in their climate policy plans.")
# ### Function to create spider graph ###
# # Create right number of columns
# n = len(df_cleaned.Country.unique())
# # We want to have max five graphs in a row
# n_rows = round(n / 5)
# col_count = 1
# for country in df_cleaned.Country.unique():
# # Get data
# df_target = df_sorted_high_level_target[df_sorted_high_level_target['Country'] == country]
# df_target['group'] = df_target['group'].apply(lambda x: x.replace("t_", ""))
# df_all = df_sorted_high_level_all[df_sorted_high_level_all['Country'] == country]
# df_all['group'] = df_all['group'].apply(lambda x: x.replace("All_c_", ""))
# with st.f"col{col_count}" =
# # Add title
# st.subheader(selected_country)
# # Create graph
# create_spider_graph(df_target, df_all, "Count", "Count")
# if col_count < 5:
# col_count +=1
# else:
# col_count = 1