lyimo commited on
Commit
7f8b654
·
verified ·
1 Parent(s): 8917188

Update part2_visualization.py

Browse files
Files changed (1) hide show
  1. part2_visualization.py +84 -110
part2_visualization.py CHANGED
@@ -4,7 +4,6 @@ import folium
4
  from folium import plugins
5
  import numpy as np
6
  import branca.colormap as cm
7
- from datetime import datetime, timedelta
8
 
9
  class VisualizationHandler:
10
  def __init__(self, optimal_conditions):
@@ -21,21 +20,20 @@ class VisualizationHandler:
21
  ]
22
 
23
  def create_interactive_plots(self, df):
24
- """Create enhanced interactive Plotly visualizations with pattern emphasis"""
25
  fig = make_subplots(
26
- rows=5, cols=1,
27
  subplot_titles=(
28
- '<b>Temperature (°C)</b>',
29
- '<b>Humidity (%)</b>',
30
- '<b>Rainfall (mm/day)</b>',
31
- '<b>Vegetation Index (NDVI)</b>',
32
- '<b>Growing Suitability</b>'
33
  ),
34
  vertical_spacing=0.08,
35
- row_heights=[0.23, 0.19, 0.19, 0.19, 0.20]
36
  )
37
 
38
- # Add temperature visualization with range
39
  self.add_temperature_plot(fig, df)
40
 
41
  # Add humidity visualization
@@ -44,18 +42,15 @@ class VisualizationHandler:
44
  # Add rainfall visualization
45
  self.add_rainfall_plot(fig, df)
46
 
47
- # Add NDVI visualization
48
- self.add_ndvi_plot(fig, df)
49
-
50
- # Add suitability visualization
51
- self.add_suitability_plot(fig, df)
52
-
53
  # Update layout
54
  fig.update_layout(
55
- height=1200,
56
  showlegend=True,
57
  title={
58
- 'text': "Weather Patterns and Agricultural Conditions Analysis",
59
  'y':0.95,
60
  'x':0.5,
61
  'xanchor': 'center',
@@ -75,23 +70,22 @@ class VisualizationHandler:
75
  margin=dict(l=60, r=30, t=100, b=60)
76
  )
77
 
78
- # Add season shading for all plots
79
  self.add_season_shading(fig, df)
80
 
81
- # Update axes
82
  fig.update_xaxes(showgrid=True, gridwidth=1, gridcolor='rgba(0,0,0,0.1)')
83
  fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor='rgba(0,0,0,0.1)')
84
 
85
  return fig
86
 
87
  def add_temperature_plot(self, fig, df):
88
- """Add detailed temperature visualization"""
89
  # Temperature range area
90
  fig.add_trace(
91
  go.Scatter(
92
  x=df['date'],
93
  y=df['temp_max'],
94
- name='Max Temperature',
95
  line=dict(color='rgba(255,0,0,0.0)'),
96
  showlegend=False
97
  ),
@@ -102,16 +96,15 @@ class VisualizationHandler:
102
  go.Scatter(
103
  x=df['date'],
104
  y=df['temp_min'],
105
- name='Temperature Range',
106
  fill='tonexty',
107
  fillcolor='rgba(255,0,0,0.1)',
108
- line=dict(color='rgba(255,0,0,0.0)'),
109
- showlegend=True
110
  ),
111
  row=1, col=1
112
  )
113
-
114
- # Main temperature line
115
  fig.add_trace(
116
  go.Scatter(
117
  x=df['date'],
@@ -122,26 +115,31 @@ class VisualizationHandler:
122
  ),
123
  row=1, col=1
124
  )
125
-
126
- # Add optimal range
127
- fig.add_hline(
128
- y=self.optimal_conditions['temperature']['min'],
129
- line_dash="dash",
130
- line_color="green",
131
- annotation_text="Min Optimal",
132
- row=1, col=1
133
- )
134
- fig.add_hline(
135
- y=self.optimal_conditions['temperature']['max'],
136
- line_dash="dash",
137
- line_color="green",
138
- annotation_text="Max Optimal",
139
  row=1, col=1
140
  )
141
 
 
 
 
 
 
 
 
 
 
 
142
  def add_humidity_plot(self, fig, df):
143
- """Add humidity visualization with pattern emphasis"""
144
- # Add main humidity line
145
  fig.add_trace(
146
  go.Scatter(
147
  x=df['date'],
@@ -153,77 +151,56 @@ class VisualizationHandler:
153
  row=2, col=1
154
  )
155
 
156
- # Add rolling average
157
  fig.add_trace(
158
  go.Scatter(
159
  x=df['date'],
160
  y=df['humidity_7day_avg'],
161
- name='7-day Humidity Trend',
162
  line=dict(color='darkblue', width=1, dash='dot'),
163
  mode='lines'
164
  ),
165
  row=2, col=1
166
  )
167
 
 
 
 
 
 
 
 
 
 
 
168
  def add_rainfall_plot(self, fig, df):
169
- """Add enhanced rainfall visualization"""
170
- # Add rainfall bars
171
  fig.add_trace(
172
  go.Bar(
173
  x=df['date'],
174
  y=df['rainfall'],
175
- name='Rainfall',
176
- marker_color='blue',
177
  opacity=0.6
178
  ),
179
  row=3, col=1
180
  )
181
-
182
- # Add cumulative rainfall line
183
- cumulative_rainfall = df['rainfall'].cumsum()
184
  fig.add_trace(
185
  go.Scatter(
186
  x=df['date'],
187
- y=cumulative_rainfall,
188
- name='Cumulative Rainfall',
189
- line=dict(color='darkblue', width=1, dash='dot'),
190
- yaxis='y2'
191
  ),
192
  row=3, col=1
193
  )
194
 
195
- def add_ndvi_plot(self, fig, df):
196
- """Add NDVI visualization with confidence bands"""
197
- # Calculate confidence bands
198
- ndvi_std = df['estimated_ndvi'].std()
199
- upper_band = df['estimated_ndvi'] + ndvi_std
200
- lower_band = df['estimated_ndvi'] - ndvi_std
201
-
202
- # Add NDVI line with confidence band
203
- fig.add_trace(
204
- go.Scatter(
205
- x=df['date'],
206
- y=upper_band,
207
- name='NDVI Upper Band',
208
- line=dict(color='rgba(0,100,0,0)'),
209
- showlegend=False
210
- ),
211
- row=4, col=1
212
- )
213
-
214
- fig.add_trace(
215
- go.Scatter(
216
- x=df['date'],
217
- y=lower_band,
218
- name='NDVI Confidence',
219
- fill='tonexty',
220
- fillcolor='rgba(0,100,0,0.1)',
221
- line=dict(color='rgba(0,100,0,0)'),
222
- showlegend=True
223
- ),
224
- row=4, col=1
225
- )
226
-
227
  fig.add_trace(
228
  go.Scatter(
229
  x=df['date'],
@@ -235,22 +212,20 @@ class VisualizationHandler:
235
  row=4, col=1
236
  )
237
 
238
- def add_suitability_plot(self, fig, df):
239
- """Add growing suitability visualization"""
240
  fig.add_trace(
241
  go.Scatter(
242
  x=df['date'],
243
  y=df['daily_suitability'],
244
  name='Growing Suitability',
245
  line=dict(color='purple', width=2),
246
- fill='tozeroy',
247
- fillcolor='rgba(128,0,128,0.1)'
248
  ),
249
- row=5, col=1
250
  )
251
 
252
  def add_season_shading(self, fig, df):
253
- """Add season shading to all plots"""
254
  seasons = df['season'].unique()
255
  season_colors = {
256
  'Main': 'rgba(0,255,0,0.1)', # Green
@@ -262,19 +237,20 @@ class VisualizationHandler:
262
  for season in seasons:
263
  season_data = df[df['season'] == season]
264
  if not season_data.empty:
265
- fig.add_vrect(
266
- x0=season_data['date'].iloc[0],
267
- x1=season_data['date'].iloc[-1],
268
- fillcolor=season_colors[season],
269
- layer="below",
270
- line_width=0,
271
- annotation_text=season,
272
- annotation_position="top left",
273
- row="all"
274
- )
 
275
 
276
  def create_enhanced_map(self, lat, lon, score, ndvi_value):
277
- """Create an interactive map with enhanced visualizations"""
278
  m = folium.Map(location=[lat, lon], zoom_start=13)
279
 
280
  # Add measurement tools
@@ -312,20 +288,18 @@ class VisualizationHandler:
312
  folium.Circle(
313
  radius=radius,
314
  location=[lat, lon],
315
- popup=f'Growing Suitability: {score:.2f}',
316
  color=score_color,
317
  fill=False,
318
  weight=2
319
  ).add_to(m)
320
 
321
- # Add heat map layer control
322
- folium.LayerControl().add_to(m)
323
-
324
  # Add mini map
325
  minimap = plugins.MiniMap()
326
  m.add_child(minimap)
327
 
328
- # Add colormap to map
 
329
  m.add_child(ndvi_colormap)
330
 
331
  return m._repr_html_()
 
4
  from folium import plugins
5
  import numpy as np
6
  import branca.colormap as cm
 
7
 
8
  class VisualizationHandler:
9
  def __init__(self, optimal_conditions):
 
20
  ]
21
 
22
  def create_interactive_plots(self, df):
23
+ """Create enhanced interactive Plotly visualizations"""
24
  fig = make_subplots(
25
+ rows=4, cols=1,
26
  subplot_titles=(
27
+ '<b>Temperature Pattern (°C)</b>',
28
+ '<b>Humidity Pattern (%)</b>',
29
+ '<b>Rainfall Pattern (mm/day)</b>',
30
+ '<b>Vegetation & Suitability Patterns</b>'
 
31
  ),
32
  vertical_spacing=0.08,
33
+ row_heights=[0.28, 0.24, 0.24, 0.24]
34
  )
35
 
36
+ # Add temperature visualization
37
  self.add_temperature_plot(fig, df)
38
 
39
  # Add humidity visualization
 
42
  # Add rainfall visualization
43
  self.add_rainfall_plot(fig, df)
44
 
45
+ # Add combined NDVI and suitability visualization
46
+ self.add_combined_patterns_plot(fig, df)
47
+
 
 
 
48
  # Update layout
49
  fig.update_layout(
50
+ height=1000,
51
  showlegend=True,
52
  title={
53
+ 'text': "Agricultural Conditions Analysis with Pattern Recognition",
54
  'y':0.95,
55
  'x':0.5,
56
  'xanchor': 'center',
 
70
  margin=dict(l=60, r=30, t=100, b=60)
71
  )
72
 
73
+ # Add season shading
74
  self.add_season_shading(fig, df)
75
 
 
76
  fig.update_xaxes(showgrid=True, gridwidth=1, gridcolor='rgba(0,0,0,0.1)')
77
  fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor='rgba(0,0,0,0.1)')
78
 
79
  return fig
80
 
81
  def add_temperature_plot(self, fig, df):
82
+ """Add temperature visualization with range and patterns"""
83
  # Temperature range area
84
  fig.add_trace(
85
  go.Scatter(
86
  x=df['date'],
87
  y=df['temp_max'],
88
+ name='Temperature Range',
89
  line=dict(color='rgba(255,0,0,0.0)'),
90
  showlegend=False
91
  ),
 
96
  go.Scatter(
97
  x=df['date'],
98
  y=df['temp_min'],
99
+ name='Daily Range',
100
  fill='tonexty',
101
  fillcolor='rgba(255,0,0,0.1)',
102
+ line=dict(color='rgba(255,0,0,0.0)')
 
103
  ),
104
  row=1, col=1
105
  )
106
+
107
+ # Add main temperature line
108
  fig.add_trace(
109
  go.Scatter(
110
  x=df['date'],
 
115
  ),
116
  row=1, col=1
117
  )
118
+
119
+ # Add 7-day average
120
+ fig.add_trace(
121
+ go.Scatter(
122
+ x=df['date'],
123
+ y=df['temp_7day_avg'],
124
+ name='7-Day Trend',
125
+ line=dict(color='darkred', width=1, dash='dot'),
126
+ mode='lines'
127
+ ),
 
 
 
 
128
  row=1, col=1
129
  )
130
 
131
+ # Add optimal range
132
+ fig.add_hline(y=self.optimal_conditions['temperature']['min'],
133
+ line_dash="dash", line_color="green",
134
+ annotation_text="Min Optimal",
135
+ row=1, col=1)
136
+ fig.add_hline(y=self.optimal_conditions['temperature']['max'],
137
+ line_dash="dash", line_color="green",
138
+ annotation_text="Max Optimal",
139
+ row=1, col=1)
140
+
141
  def add_humidity_plot(self, fig, df):
142
+ """Add humidity visualization with patterns"""
 
143
  fig.add_trace(
144
  go.Scatter(
145
  x=df['date'],
 
151
  row=2, col=1
152
  )
153
 
 
154
  fig.add_trace(
155
  go.Scatter(
156
  x=df['date'],
157
  y=df['humidity_7day_avg'],
158
+ name='Humidity Trend',
159
  line=dict(color='darkblue', width=1, dash='dot'),
160
  mode='lines'
161
  ),
162
  row=2, col=1
163
  )
164
 
165
+ # Add optimal range
166
+ fig.add_hline(y=self.optimal_conditions['humidity']['min'],
167
+ line_dash="dash", line_color="green",
168
+ annotation_text="Min Optimal",
169
+ row=2, col=1)
170
+ fig.add_hline(y=self.optimal_conditions['humidity']['max'],
171
+ line_dash="dash", line_color="green",
172
+ annotation_text="Max Optimal",
173
+ row=2, col=1)
174
+
175
  def add_rainfall_plot(self, fig, df):
176
+ """Add rainfall visualization with patterns"""
177
+ # Daily rainfall bars
178
  fig.add_trace(
179
  go.Bar(
180
  x=df['date'],
181
  y=df['rainfall'],
182
+ name='Daily Rainfall',
183
+ marker_color='lightblue',
184
  opacity=0.6
185
  ),
186
  row=3, col=1
187
  )
188
+
189
+ # Rainfall trend
 
190
  fig.add_trace(
191
  go.Scatter(
192
  x=df['date'],
193
+ y=df['rainfall_7day_avg'],
194
+ name='Rainfall Trend',
195
+ line=dict(color='blue', width=2),
196
+ mode='lines'
197
  ),
198
  row=3, col=1
199
  )
200
 
201
+ def add_combined_patterns_plot(self, fig, df):
202
+ """Add combined NDVI and suitability visualization"""
203
+ # NDVI line
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
  fig.add_trace(
205
  go.Scatter(
206
  x=df['date'],
 
212
  row=4, col=1
213
  )
214
 
215
+ # Suitability score
 
216
  fig.add_trace(
217
  go.Scatter(
218
  x=df['date'],
219
  y=df['daily_suitability'],
220
  name='Growing Suitability',
221
  line=dict(color='purple', width=2),
222
+ mode='lines'
 
223
  ),
224
+ row=4, col=1
225
  )
226
 
227
  def add_season_shading(self, fig, df):
228
+ """Add season indicators to all plots"""
229
  seasons = df['season'].unique()
230
  season_colors = {
231
  'Main': 'rgba(0,255,0,0.1)', # Green
 
237
  for season in seasons:
238
  season_data = df[df['season'] == season]
239
  if not season_data.empty:
240
+ for row in range(1, 5):
241
+ fig.add_vrect(
242
+ x0=season_data['date'].iloc[0],
243
+ x1=season_data['date'].iloc[-1],
244
+ fillcolor=season_colors[season],
245
+ layer="below",
246
+ line_width=0,
247
+ annotation_text=season if row == 1 else None,
248
+ annotation_position="top left",
249
+ row=row, col=1
250
+ )
251
 
252
  def create_enhanced_map(self, lat, lon, score, ndvi_value):
253
+ """Create an interactive map with both weather and vegetation analysis"""
254
  m = folium.Map(location=[lat, lon], zoom_start=13)
255
 
256
  # Add measurement tools
 
288
  folium.Circle(
289
  radius=radius,
290
  location=[lat, lon],
291
+ popup=f'Suitability Score: {score:.2f}',
292
  color=score_color,
293
  fill=False,
294
  weight=2
295
  ).add_to(m)
296
 
 
 
 
297
  # Add mini map
298
  minimap = plugins.MiniMap()
299
  m.add_child(minimap)
300
 
301
+ # Add layer control
302
+ folium.LayerControl().add_to(m)
303
  m.add_child(ndvi_colormap)
304
 
305
  return m._repr_html_()