johnbakerjr commited on
Commit
97d64bb
1 Parent(s): 64d5725

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +220 -0
app.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+
4
+ from dataprep.clean import clean_country
5
+ import plotly.graph_objects as go
6
+
7
+ gdp_per_capita = pd.read_csv('./data/country_gdp_per_capita_worldbank.csv')
8
+ gdp_per_capita = gdp_per_capita[['Country Name', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018', '2019', '2020']]
9
+
10
+ usa = pd.read_csv('./data/USAData_RenewableInvestment_2010-2020.csv').set_index('Country')
11
+
12
+ ## read plotly data ##
13
+
14
+ temp_delta_plotly = pd.read_csv('./data/Annual_Surface_Temperature_Change.csv')
15
+ invest_plotly = pd.read_csv('data/Environmental_Protection_Expenditures.csv')
16
+ gdp_per_capita_plotly = gdp_per_capita.copy()
17
+
18
+ ## prepare data for plotly ##
19
+
20
+ gdp_per_capita_plotly = gdp_per_capita_plotly.rename(columns={'Country Name': 'Country'})
21
+
22
+ # look up ISO3 codes for countries
23
+ gdp_per_capita_plotly = clean_country(gdp_per_capita_plotly, "Country", output_format="alpha-3").rename(columns={'Country_clean': 'ISO3'})
24
+ gdp_per_capita_plotly = gdp_per_capita_plotly[['Country', 'ISO3', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018', '2019', '2020']]
25
+ gdp_per_capita_plotly = gdp_per_capita_plotly.rename(columns={'2010': 2010, '2011': 2011, '2012': 2012, '2013': 2013, '2014': 2014, '2015': 2015, '2016': 2016, '2017': 2017, '2018': 2018, '2019': 2019, '2020': 2020})
26
+
27
+ temp_delta_plotly = temp_delta_plotly[['Country', 'ISO3', 'F2010', 'F2011', 'F2012', 'F2013', 'F2014', 'F2015', 'F2016', 'F2017', 'F2018', 'F2019', 'F2020']]
28
+ temp_delta_plotly = temp_delta_plotly.rename(columns={'F2010': 2010, 'F2011': 2011, 'F2012': 2012, 'F2013': 2013, 'F2014': 2014, 'F2015': 2015, 'F2016': 2016, 'F2017': 2017, 'F2018': 2018, 'F2019': 2019, 'F2020': 2020})
29
+
30
+ usa2 = usa.copy().reset_index()
31
+ usa2['ISO3'] = 'USA'
32
+ invest_plotly = invest_plotly[invest_plotly['Unit'] == 'Percent of GDP'].fillna(int(0))
33
+ invest_plotly = invest_plotly[['Country', 'ISO3', 'F2010', 'F2011', 'F2012', 'F2013', 'F2014', 'F2015', 'F2016', 'F2017', 'F2018', 'F2019', 'F2020']].reset_index(drop=True)
34
+ invest_plotly = pd.concat([invest_plotly, usa2])
35
+ invest_plotly = invest_plotly.groupby(['ISO3']).agg('sum').reset_index()
36
+ invest_plotly = invest_plotly.rename(columns={'F2010': 2010, 'F2011': 2011, 'F2012': 2012, 'F2013': 2013, 'F2014': 2014, 'F2015': 2015, 'F2016': 2016, 'F2017': 2017, 'F2018': 2018, 'F2019': 2019, 'F2020': 2020})
37
+
38
+ temp_delta_plotly = temp_delta_plotly.melt(id_vars=['ISO3'], value_vars=[2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020], var_name='Year', value_name='Temp_Change')
39
+ gdp_per_capita_plotly = gdp_per_capita_plotly.melt(id_vars=['ISO3', 'Country'], value_vars=[2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020], var_name='Year', value_name='GDP_Per_Capita')
40
+ invest_plotly = invest_plotly.melt(id_vars=['ISO3'], value_vars=[2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020], var_name='Year', value_name='Investment_Percent')
41
+
42
+ plotly_data = pd.merge(temp_delta_plotly, invest_plotly, on=['ISO3', 'Year'])
43
+ plotly_data = pd.merge(gdp_per_capita_plotly, plotly_data, on=['ISO3', 'Year'])
44
+
45
+ # drop all YEMEN data, as there is missing GDP data and no temp_change data
46
+ plotly_data = plotly_data.drop(plotly_data.loc[plotly_data['ISO3']=='YEM'].index)
47
+
48
+ # drop 2010-2012 data for SOMALIA, as there is no GDP data
49
+ plotly_data = plotly_data.drop(plotly_data.loc[(plotly_data['ISO3']=='SOM') & (plotly_data['Year']<2013)].index)
50
+
51
+ new_country_data = plotly_data.copy()
52
+ new_country_data = new_country_data.groupby('Country').agg({'Temp_Change': 'mean', 'Investment_Percent': 'mean', 'GDP_Per_Capita': 'mean'})
53
+ new_country_data['Temp_Change'] = new_country_data['Temp_Change'] + .25
54
+ new_country_data = new_country_data.rename(columns={'Temp_Change': 'temp_delta_avg', 'Investment_Percent': 'renew_invest_avg', 'GDP_Per_Capita': 'gdp_per_capita_avg'})
55
+
56
+ g20 = ['Argentina', 'Australia', 'Brazil', 'Canada', 'China', 'France', 'Germany', 'India', 'Indonesia', 'Italy', 'Japan', 'Republic of Korea', 'Mexico', 'Russia', 'Saudi Arabia', 'South Africa', 'Turkey', 'United Kingdom', 'United States', 'Austria', 'Belgium', 'Bulgaria', 'Croatia', 'Cyprus', 'Czech Republic', 'Denmark', 'Estonia', 'Finland', 'Greece', 'Hungary', 'Ireland', 'Latvia', 'Lithuania', 'Luxembourg', 'Malta', 'Netherlands', 'Poland', 'Portugal', 'Romania', 'Slovakia', 'Slovenia', 'Spain', 'Sweden']
57
+ new_country_data['g20'] = new_country_data.index.isin(g20).tolist()
58
+
59
+ g20_countries = new_country_data.loc[new_country_data['g20'] == True].index.to_list()
60
+
61
+
62
+ plotly_data['Temp_Change'] = plotly_data['Temp_Change'] + .25
63
+
64
+ p1 = (plotly_data['Investment_Percent'] > 2)
65
+ p2 = (plotly_data['Temp_Change'] < 1.5)
66
+
67
+ plotly_data['color_code'] = np.where(p1 & p2, '#46725D', "False")
68
+ plotly_data['color_code'] = np.where(p1 & ~p2, '#A46D13', plotly_data['color_code'])
69
+ plotly_data['color_code'] = np.where(~p1 & p2, '#505693', plotly_data['color_code'])
70
+ plotly_data['color_code'] = np.where(~p1 & ~p2, '#9A381D', plotly_data['color_code'])
71
+
72
+ # make plotly figure
73
+
74
+ dataset = plotly_data.copy()
75
+
76
+ years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020]
77
+
78
+ # make figure
79
+ fig_dict = {
80
+ "data": [],
81
+ "layout": {},
82
+ "frames": []
83
+ }
84
+
85
+ min_x_val = dataset['Temp_Change'].min()-.2
86
+ max_x_val = dataset['Temp_Change'].max()+.2
87
+ min_y_val = dataset['Investment_Percent'].min()-.2
88
+ max_y_val = dataset['Investment_Percent'].max()+.2
89
+
90
+ # fill in most of layout
91
+ fig_dict["layout"]["xaxis"] = {"range": [min_x_val, max_x_val], "title": f'Annual Temperature Above Pre-industrial Levels ({chr(176)}C)'}
92
+ fig_dict["layout"]["yaxis"] = {"range": [min_y_val, 4.5], "title": "Investment in Renewable Energy (% GDP)"} # "type": "log" makes y-axis log scale
93
+ fig_dict["layout"]["hovermode"] = "closest"
94
+ fig_dict["layout"]["updatemenus"] = [
95
+ {
96
+ "buttons": [
97
+ {
98
+ "args": [None, {"frame": {"duration": 700, "redraw": False},
99
+ "fromcurrent": True, "transition": {"duration": 500,
100
+ "easing": "quadratic-in-out"}}],
101
+ "label": "Play",
102
+ "method": "animate"
103
+ },
104
+ {
105
+ "args": [[None], {"frame": {"duration": 0, "redraw": False},
106
+ "mode": "immediate",
107
+ "transition": {"duration": 0}}],
108
+ "label": "Pause",
109
+ "method": "animate"
110
+ }
111
+ ],
112
+ "direction": "left",
113
+ "pad": {"r": 10, "t": 87},
114
+ "showactive": False,
115
+ "type": "buttons",
116
+ "x": 0.1,
117
+ "xanchor": "right",
118
+ "y": 0,
119
+ "yanchor": "top"
120
+ }
121
+ ]
122
+
123
+ sliders_dict = {
124
+ "active": 0,
125
+ "yanchor": "top",
126
+ "xanchor": "left",
127
+ "currentvalue": {
128
+ "font": {"size": 20},
129
+ "prefix": "Year:",
130
+ "visible": True,
131
+ "xanchor": "right"
132
+ },
133
+ "transition": {"duration": 300, "easing": "cubic-in-out"},
134
+ "pad": {"b": 10, "t": 50},
135
+ "len": 0.9,
136
+ "x": 0.1,
137
+ "y": 0,
138
+ "steps": []
139
+ }
140
+
141
+ Countries = list(plotly_data['Country'].unique())
142
+ Countries = sorted(Countries)
143
+
144
+ # make data
145
+ year = 2010
146
+ for Country in g20_countries:
147
+ dataset_by_year = dataset[dataset["Year"] == year]
148
+ dataset_by_year_and_country = dataset_by_year[
149
+ dataset_by_year["Country"] == Country]
150
+
151
+ data_dict = {
152
+ "x": list(dataset_by_year_and_country["Temp_Change"]),
153
+ "y": list(dataset_by_year_and_country["Investment_Percent"]),
154
+ "mode": "markers",
155
+ "marker": {
156
+ "sizemode": "area",
157
+ "sizeref": 300,
158
+ "size": list(dataset_by_year_and_country["GDP_Per_Capita"]),
159
+ "color": dataset_by_year_and_country.loc[dataset_by_year_and_country['Country']==Country].color_code[dataset_by_year_and_country['Year']==year]
160
+ },
161
+ "name": Country
162
+ }
163
+ fig_dict["data"].append(data_dict)
164
+
165
+ # make frames
166
+ for year in years:
167
+ frame = {"data": [], "name": str(year)}
168
+ for Country in g20_countries:
169
+ dataset_by_year = dataset[dataset["Year"] == int(year)]
170
+ dataset_by_year_and_country = dataset_by_year[
171
+ dataset_by_year["Country"] == Country]
172
+
173
+ data_dict = {
174
+ "x": list(dataset_by_year_and_country["Temp_Change"]),
175
+ "y": list(dataset_by_year_and_country["Investment_Percent"]),
176
+ "mode": "markers",
177
+ "marker": {
178
+ "sizemode": "area",
179
+ "sizeref": 300,
180
+ "size": list(dataset_by_year_and_country["GDP_Per_Capita"]),
181
+ "color": dataset_by_year_and_country.loc[dataset_by_year_and_country['Country']==Country].color_code[dataset_by_year_and_country['Year']==year]
182
+ },
183
+ "name": Country
184
+ }
185
+ frame["data"].append(data_dict)
186
+
187
+ fig_dict["frames"].append(frame)
188
+ slider_step = {"args": [
189
+ [year],
190
+ {"frame": {"duration": 1500, "redraw": False},
191
+ "mode": "immediate",
192
+ "transition": {"duration": 1500}}
193
+ ],
194
+ "label": year,
195
+ "method": "animate"}
196
+ sliders_dict["steps"].append(slider_step)
197
+
198
+
199
+ fig_dict["layout"]["sliders"] = [sliders_dict]
200
+
201
+ fig = go.Figure(fig_dict)
202
+
203
+ fig.add_hline(y=2, line_dash="dash", line_color="black", annotation_text="Investment Needed to Fully Transition to Renewable Energy by 2050", annotation_position="bottom right")
204
+ fig.add_vline(x=1.5, line_dash="dash", line_color="black", annotation_text="2050 Target Temperature Increase", annotation_position="top right")
205
+ fig.add_annotation(x=3.75, y=-.35, text="Urgent Action Needed", showarrow=False, font_size=12, bordercolor='#9A381D', font=dict(color='#9A381D'), borderpad=3)
206
+ fig.add_annotation(x=3.67, y=4.1, text="Continued Progress Needed", showarrow=False, font_size=12, bordercolor='#A46D13', font=dict(color='#A46D13'), borderpad=3)
207
+ fig.add_annotation(x=0.2, y=4.1, text="Meeting 2050 Climate Goals", showarrow=False, font_size=12, bordercolor='#46725D', font=dict(color='#46725D'), borderpad=3)
208
+ fig.add_annotation(x=0.17, y=-.35, text="Investments Falling Short", showarrow=False, font_size=12, bordercolor='#505693', font=dict(color='#505693'), borderpad=3)
209
+
210
+ fig.update_layout(
211
+ title={
212
+ 'text': "G20 Countries Have Invested Little as Temperatures Dramatically Increased Over the Last Decade",
213
+ 'y':0.9,
214
+ 'x':0.5,
215
+ 'xanchor': 'center',
216
+ 'yanchor': 'top'},
217
+ showlegend=False
218
+ )
219
+
220
+ fig.show()