-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclimate_change.py
237 lines (215 loc) · 11.7 KB
/
climate_change.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
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import pandas as pd
import numpy as np
import plotly.graph_objs as go
from dash.dependencies import Input, Output
app = dash.Dash()
#! data manipulation
country = pd.read_csv('Climate_Change_Dash/Data_climate/GlobalLandTemperaturesByCountry.csv')
majorcity = pd.read_csv('Climate_Change_Dash/Data_climate/GlobalLandTemperaturesByMajorCity.csv')
state = pd.read_csv('Climate_Change_Dash/Data_climate/GlobalLandTemperaturesByState.csv')
globe = pd.read_csv('Climate_Change_Dash/Data_climate/GlobalTemperatures.csv')
CO2 = pd.read_csv('Climate_Change_Dash/Data_climate/global_co2_emissions_per_capita.csv')
#* unique country name to for dropdown loop
country_name = country.Country.unique().tolist()
majorcity_name = majorcity.City.unique().tolist()
state_name = state.State.unique().tolist()
#* it doesn't make sense to visualize temp throughout all the time. The seasonality is confusing and making my graphs not straightforward
# this is global years
years = np.unique(globe['dt'].apply(lambda x: x[:4])) # the first four characters
mean_temp_globe = []
for year in years:
mean_temp_globe.append(globe[globe['dt'].apply(lambda x: x[:4]) == year]['LandAverageTemperature'].mean()) # average all temperatures in the same year
# prepare data for plotly graph of global average temperature
data_global = go.Scatter(x = years,
y = mean_temp_globe,
name='Average Temperature',
line=dict(color='rgb(199, 121, 093)')
)
# prepare co2 emission data for future visualization
years_co2 = CO2['date'].tolist()
Emission = CO2['Global CO2 Emissions per Capita'].tolist()
data_co2 = go.Scatter(x = years_co2,
y = Emission,
name='Global CO2 Emission per capita',
line=dict(color='rgb(199, 121, 093)')
)
#! layout
app.layout = html.Div([
# Main title
html.H1('Climate Change Data Analysis', style = {'textAlign': 'center'}), #css
# dividing into tabs
dcc.Tabs(id = 'tabs', children = [
# Defining the layout of the first Tab
dcc.Tab(label = 'Local', children = [
html.Div([
dcc.Markdown(''' This is my CS 106 Project at Calvin University, proving the global warming trend.'''),
#! Country
html.H1('Temperature VS Country', style = {'textAlign': 'center'}),
#FIRST dropdown. Country
dcc.Dropdown(id = 'my-dropdown1', # used to connect with callback
options=[{'label': i, 'value': i} for i in country_name], # label is what user sees; value is what I work with inside dash code
multi=True,value=['China'], #value is default value
style = {"display": "block", "margin-left": "auto",
"margin-right": "auto", "width": "60%"}),
dcc.Graph(id = 'Temp_country'),
#! State
html.H1('Temperature VS State', style = {'textAlign': 'center'}),
#Second dropdown. State
dcc.Dropdown(id = 'my-dropdown2', # used to connect with callback
options=[{'label': i, 'value': i} for i in state_name], # label is what user sees; value is what I work with inside dash code
multi=True,value=['Acre'], #value is default value
style = {"display": "block", "margin-left": "auto",
"margin-right": "auto", "width": "60%"}),
dcc.Graph(id = 'Temp_state'),
#! Major City
html.H1('Temperature VS Major City', style = {'textAlign': 'center'}),
#Third dropdown. City
dcc.Dropdown(id = 'my-dropdown3', # used to connect with callback
options=[{'label': i, 'value': i} for i in majorcity_name], # label is what user sees; value is what I work with inside dash code
multi=True,value=['Abidjan'], #value is default value
style = {"display": "block", "margin-left": "auto",
"margin-right": "auto", "width": "60%"}),
dcc.Graph(id = 'Temp_City'),
]) # html.div
]), # dcc.tab1
#! Second tab for CO2 emission
#* this one does not have to be interactive. Simple two ploty graphs
dcc.Tab(label = "Global", children = [
html.Div([
html.H1("Climate Change on a Global Perspective", style={"textAlign": "center"}),
dcc.Graph(id = "Temp_globe",
figure = {'data': [data_global],
'layout': go.Layout(colorway=["#5E0DAC", '#FF4F00', '#375CB1',
'#FF7400', '#FFF400', '#FF0056'],
height=600,
title=f"Global Temperature Over Time",
xaxis={"title":"Year"},
yaxis={"title":"Temperature(Celsius)"}
)
}
),
dcc.Graph(id = 'CO2_Emission',
figure = {'data': [data_co2],
'layout': go.Layout(colorway=["#5E0DAC", '#FF4F00', '#375CB1',
'#FF7400', '#FFF400', '#FF0056'],
height=600,
title=f"Global CO2 Emission Over Time",
xaxis={"title":"Year"},
yaxis={"title":"Global CO2 Emission per capita"}
)
}
)
])# html.Div for dcc.tab2
]) # dcc.tab2
]) # dcc.tabs
]) #html.div
#! Interactive part
@app.callback(Output('Temp_country', 'figure'),
[Input('my-dropdown1', 'value')])
#! Country
def update_graph(selected_dropdown):
dropdown = dict(zip(country_name, country_name))
trace_1 = []
for c in selected_dropdown:
trace_1.append(
go.Scatter(
x = country[country['Country'] == c]['dt'],
y = country[country['Country'] == c]['AverageTemperature'],
mode = 'lines', opacity = 0.7,
name = f'Temperature of {dropdown[c]}',
textposition = 'bottom center'
)
)
traces = [trace_1]
data = [val for sublist in traces for val in sublist] # flattening. Cited from https://towardsdatascience.com/interactive-dashboards-for-data-science-51aa038279e5
figure = {'data': data,
'layout': go.Layout(colorway=["#5E0DAC", '#FF4F00', '#375CB1',
'#FF7400', '#FFF400', '#FF0056'],
height=600,
title=f"Temperature of {', '.join(str(dropdown[i]) for i in selected_dropdown)} Over Time",
xaxis={"title":"Date",
'rangeselector': {'buttons': list([{'count': 1, 'label': '1M',
'step': 'month',
'stepmode': 'backward'},
{'count': 6, 'label': '6M',
'step': 'month',
'stepmode': 'backward'},
{'step': 'all'}])},
'rangeslider': {'visible': True}, 'type': 'date'},
yaxis={"title":"Temperature(Celsius)"})}
return figure
#! State
@app.callback(Output('Temp_state', 'figure'),
[Input('my-dropdown2', 'value')])
def update_graph(selected_dropdown):
dropdown = dict(zip(state_name, state_name))
trace_1 = [] # simply a randomly named list for to contain future data
for c in selected_dropdown:
trace_1.append(
go.Scatter(
x = state[state['State'] == c]['dt'],
y = state[state['State'] == c]['AverageTemperature'], # thinking if I should use autorange
mode = 'lines', opacity = 0.7,
name = f'Temperature of {dropdown[c]}', # so that title would change as I add more countries
textposition = 'bottom center'
)
)
traces = [trace_1]
data = [val for sublist in traces for val in sublist]
figure = {'data': data,
'layout': go.Layout(colorway=["#5E0DAC", '#FF4F00', '#375CB1',
'#FF7400', '#FFF400', '#FF0056'],
height=600,
title=f"Temperature of {', '.join(str(dropdown[i]) for i in selected_dropdown)} Over Time",
xaxis={"title":"Date",
'rangeselector': {'buttons': list([{'count': 1, 'label': '1M',
'step': 'month',
'stepmode': 'backward'},
{'count': 6, 'label': '6M',
'step': 'month',
'stepmode': 'backward'},
{'step': 'all'}])},
'rangeslider': {'visible': True}, 'type': 'date'},
yaxis={"title":"Temperature(Celsius)"})}
return figure
#! City
@app.callback(Output('Temp_City', 'figure'),
[Input('my-dropdown3', 'value')])
def update_graph(selected_dropdown):
dropdown = dict(zip(majorcity_name, majorcity_name))
trace_1 = []
for c in selected_dropdown:
trace_1.append(
go.Scatter(
x = majorcity[majorcity['City'] == c]['dt'],
y = majorcity[majorcity['City'] == c]['AverageTemperature'], # thinking if I should use autorange
mode = 'lines', opacity = 0.7,
name = f'Temperature of {dropdown[c]}',
textposition = 'bottom center'
)
)
traces = [trace_1]
data = [val for sublist in traces for val in sublist]
figure = {'data': data,
'layout': go.Layout(colorway=["#5E0DAC", '#FF4F00', '#375CB1',
'#FF7400', '#FFF400', '#FF0056'],
height=600,
title=f"Temperature of {', '.join(str(dropdown[i]) for i in selected_dropdown)} Over Time",
xaxis={"title":"Date",
'rangeselector': {'buttons': list([{'count': 1, 'label': '1M',
'step': 'month',
'stepmode': 'backward'},
{'count': 6, 'label': '6M',
'step': 'month',
'stepmode': 'backward'},
{'step': 'all'}])},
#'rangeslider': {'visible': True}, 'type': 'date'
},
yaxis={"title":"Temperature(Celsius)"})}
return figure
if __name__ == "__main__":
app.run_server(debug=True)