-
Notifications
You must be signed in to change notification settings - Fork 1
/
map_gen.py
224 lines (163 loc) · 5.35 KB
/
map_gen.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
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import plotly.plotly as py
import plotly.graph_objs as go
import plotly.offline
from config import mapbox_api_key
import pandas as pd
import numpy as np
from pytz import timezone
import pytz
from datetime import datetime as dt
# # Mapping functions:
# In[36]:
def utc_to_pst(date):
d = pytz.utc.localize(date)
pst = d.astimezone(timezone('US/Pacific'))
parsed_pst = dt.strftime(pst, '%Y-%m-%d %I:%M %p')
return parsed_pst
def check_col(df,col):
'''Checks column and returns appropriate parameters for mapping.'''
size = df[col]
colorscale = 'Jet'
reversescale=False
if col == 'rain':
string = "{}<br>Value: {}mm<br>Date: {}"
size = df[col]*4
colorscale = 'Blues'
reversescale=True
elif col == 'wind_speed':
string = "{}<br>Value: {}m/s<br>Date: {}"
size = df[col]*1.5
elif col == 'temperature':
string = "{}<br>Value: {}\u00b0F<br>Date: {}"
size = df[col]/3
elif col == 'cloud':
string = "{}<br>Percentage: {}%<br>Date: {}"
size = df[col]/1.5
colorscale = 'Blues'
elif col == 'pressure':
string = "{}<br>Value: {}hPa<br>Date: {}"
size = df[col]/100
colorscale='YlGnBu'
elif col == 'aqi':
string = "{}<br>Value: {}<br>{}<br>Dominant pollutant: {}<br>Date: {}"
size = df[col]/10
else:
string = "{}<br>Value: {}mW/m\u00b2<br>Date: {}"
size = df[col]*2
return size,string,colorscale,reversescale
# In[8]:
def marker_text(df,col,fstring):
'''
Generates hover-over text for weather info.
'''
text = []
for row in df.itertuples():
if col == 'aqi':
a = getattr(row, "city")
b = getattr(row, col)
c = getattr(row, "category")
d = getattr(row, "dominant_pollutant")
e = utc_to_pst(getattr(row, "date"))
marker_text = fstring.format(a,b,c,d,e)
text.append(marker_text)
else:
a = getattr(row, "city")
b = getattr(row, col)
c = utc_to_pst(getattr(row, "date"))
marker_text = fstring.format(a,b,c)
text.append(marker_text)
return text
# In[34]:
def make_traces(df,columns):
'''
Generates traces from weather data.
'''
data = []
for column in columns:
# Return appropriate data and layout for each column.
size,string,colorscale,reversescale = check_col(df,column)
# Display first trace instead of all data at once.
if column == columns[0]:
visible = True
else:
visible = 'legendonly'
trace = go.Scattermapbox(
lat=round(df['lat'],3),
lon=round(df['lng'],3),
mode='markers',
marker=dict(
size=size,
color= size,
colorscale = colorscale,
reversescale=reversescale
),
text= marker_text(df,column,string),
name=column,
visible=visible
)
data.append(trace)
return data
# In[10]:
def make_conditions(col_list):
''' Returns an array with lists of conditions for dropdown menus.'''
# Make array full of False values with dimensions of input list.
array = np.full(shape=(len(col_list),len(col_list)), fill_value=False, dtype=bool)
for i in range(len(array)):
array[i][i] = True
return array
# In[11]:
def menu_buttons(labels,conditions):
'''Returns a list of buttons for dropdown menus in scattermap.'''
buttons = []
for label,condition in zip(labels,conditions):
dic = {'label':label,
'method':'update',
'args':[{'visible': condition}]}
buttons.append(dic)
return buttons
# In[37]:
def generate_scattermap(df):
# lists for menu and for actual plotting.
menu_categories = ['UV Index', 'AQI', 'Temperature', 'Cloud', 'Pressure', 'Wind Speed', 'Rain']
plot_columns = ['uv_index', 'aqi','temperature', 'cloud','pressure', 'wind_speed', 'rain']
# Menu options for dropdown menu.
conditions = make_conditions(menu_categories)
buttons = menu_buttons(menu_categories,conditions)
data = make_traces(df,plot_columns)
updatemenus = list([
dict(
buttons=buttons,
x = 0.0,
xanchor = 'left',
y = 1,
yanchor = 'top',
pad = {'l': 3, 't': 3},
bgcolor = '#AAAAAA',
showactive = True,
bordercolor = '#FFFFFF',
font = dict(size=11, color='#000000')
)])
layout = go.Layout(
autosize=True,
hovermode='closest',
mapbox=dict(
accesstoken=mapbox_api_key,
bearing=0,
center=dict(
lat=36,
lon=-119
),
style='dark',
pitch=0,
zoom=5
),
margin = dict( t=0, b=0, l=0, r=0 ),
updatemenus=updatemenus,
showlegend=False
)
fig = dict(data=data, layout=layout)
map_html = plotly.offline.plot(fig, include_plotlyjs=False, output_type='div')
return map_html