lyimo commited on
Commit
c6ac77f
·
verified ·
1 Parent(s): 5605efe

Update part2_visualization.py

Browse files
Files changed (1) hide show
  1. part2_visualization.py +136 -128
part2_visualization.py CHANGED
@@ -4,6 +4,7 @@ import folium
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):
@@ -21,13 +22,16 @@ class VisualizationHandler:
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]
@@ -42,15 +46,15 @@ class VisualizationHandler:
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',
@@ -73,38 +77,40 @@ class VisualizationHandler:
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
- ),
92
- row=1, col=1
93
- )
94
-
95
- fig.add_trace(
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'],
@@ -116,30 +122,31 @@ class VisualizationHandler:
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'],
@@ -150,31 +157,31 @@ class VisualizationHandler:
150
  ),
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'],
@@ -186,71 +193,72 @@ class VisualizationHandler:
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'],
207
- y=df['estimated_ndvi'],
208
- name='Vegetation Index',
209
- line=dict(color='green', width=2),
210
- mode='lines'
211
- ),
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
232
- 'Early': 'rgba(255,255,0,0.1)', # Yellow
233
- 'Late': 'rgba(255,165,0,0.1)', # Orange
234
- 'Dry': 'rgba(255,0,0,0.1)' # Red
235
- }
236
-
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
 
4
  from folium import plugins
5
  import numpy as np
6
  import branca.colormap as cm
7
+ from datetime import datetime
8
 
9
  class VisualizationHandler:
10
  def __init__(self, optimal_conditions):
 
22
 
23
  def create_interactive_plots(self, df):
24
  """Create enhanced interactive Plotly visualizations"""
25
+ if df is None or df.empty:
26
+ return go.Figure() # Return empty figure if no data
27
+
28
  fig = make_subplots(
29
  rows=4, cols=1,
30
  subplot_titles=(
31
  '<b>Temperature Pattern (°C)</b>',
32
  '<b>Humidity Pattern (%)</b>',
33
  '<b>Rainfall Pattern (mm/day)</b>',
34
+ '<b>Vegetation & Suitability Indices</b>'
35
  ),
36
  vertical_spacing=0.08,
37
  row_heights=[0.28, 0.24, 0.24, 0.24]
 
46
  # Add rainfall visualization
47
  self.add_rainfall_plot(fig, df)
48
 
49
+ # Add vegetation and suitability visualization
50
+ self.add_combined_indices_plot(fig, df)
51
 
52
  # Update layout
53
  fig.update_layout(
54
  height=1000,
55
  showlegend=True,
56
  title={
57
+ 'text': "Agricultural Conditions Analysis",
58
  'y':0.95,
59
  'x':0.5,
60
  'xanchor': 'center',
 
77
  # Add season shading
78
  self.add_season_shading(fig, df)
79
 
80
+ # Update axes for all subplots
81
  fig.update_xaxes(showgrid=True, gridwidth=1, gridcolor='rgba(0,0,0,0.1)')
82
  fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor='rgba(0,0,0,0.1)')
83
 
84
  return fig
85
 
86
  def add_temperature_plot(self, fig, df):
87
+ """Add temperature visualization with range"""
88
  # Temperature range area
89
+ if 'temp_max' in df.columns and 'temp_min' in df.columns:
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
+ ),
98
+ row=1, col=1
99
+ )
100
+
101
+ fig.add_trace(
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
+ ),
110
+ row=1, col=1
111
+ )
112
 
113
+ # Main temperature line
114
  fig.add_trace(
115
  go.Scatter(
116
  x=df['date'],
 
122
  row=1, col=1
123
  )
124
 
125
+ # Add rolling average
126
+ if 'temp_7day_avg' in df.columns:
127
+ fig.add_trace(
128
+ go.Scatter(
129
+ x=df['date'],
130
+ y=df['temp_7day_avg'],
131
+ name='7-Day Average',
132
+ line=dict(color='darkred', width=1, dash='dot'),
133
+ mode='lines'
134
+ ),
135
+ row=1, col=1
136
+ )
137
 
138
  # Add optimal range
139
+ for limit_type, value in self.optimal_conditions['temperature'].items():
140
+ fig.add_hline(
141
+ y=value,
142
+ line_dash="dash",
143
+ line_color="green",
144
+ annotation_text=f"Optimal {limit_type}",
145
+ row=1, col=1
146
+ )
147
 
148
  def add_humidity_plot(self, fig, df):
149
+ """Add humidity visualization"""
150
  fig.add_trace(
151
  go.Scatter(
152
  x=df['date'],
 
157
  ),
158
  row=2, col=1
159
  )
160
+
161
+ if 'humidity_7day_avg' in df.columns:
162
+ fig.add_trace(
163
+ go.Scatter(
164
+ x=df['date'],
165
+ y=df['humidity_7day_avg'],
166
+ name='7-Day Average',
167
+ line=dict(color='darkblue', width=1, dash='dot'),
168
+ mode='lines'
169
+ ),
170
+ row=2, col=1
171
+ )
172
 
173
  # Add optimal range
174
+ for limit_type, value in self.optimal_conditions['humidity'].items():
175
+ fig.add_hline(
176
+ y=value,
177
+ line_dash="dash",
178
+ line_color="green",
179
+ annotation_text=f"Optimal {limit_type}",
180
+ row=2, col=1
181
+ )
182
 
183
  def add_rainfall_plot(self, fig, df):
184
+ """Add rainfall visualization"""
 
185
  fig.add_trace(
186
  go.Bar(
187
  x=df['date'],
 
193
  row=3, col=1
194
  )
195
 
196
+ if 'rainfall_7day_avg' in df.columns:
197
+ fig.add_trace(
198
+ go.Scatter(
199
+ x=df['date'],
200
+ y=df['rainfall_7day_avg'],
201
+ name='7-Day Average',
202
+ line=dict(color='blue', width=2),
203
+ mode='lines'
204
+ ),
205
+ row=3, col=1
206
+ )
207
 
208
+ def add_combined_indices_plot(self, fig, df):
209
+ """Add vegetation and suitability indices visualization"""
210
+ if 'estimated_ndvi' in df.columns:
211
+ fig.add_trace(
212
+ go.Scatter(
213
+ x=df['date'],
214
+ y=df['estimated_ndvi'],
215
+ name='Vegetation Index',
216
+ line=dict(color='green', width=2),
217
+ mode='lines'
218
+ ),
219
+ row=4, col=1
220
+ )
221
 
222
+ if 'daily_suitability' in df.columns:
223
+ fig.add_trace(
224
+ go.Scatter(
225
+ x=df['date'],
226
+ y=df['daily_suitability'],
227
+ name='Growing Suitability',
228
+ line=dict(color='purple', width=2),
229
+ mode='lines'
230
+ ),
231
+ row=4, col=1
232
+ )
233
 
234
  def add_season_shading(self, fig, df):
235
+ """Add season shading to all plots"""
236
+ if 'season' in df.columns:
237
+ seasons = df['season'].unique()
238
+ season_colors = {
239
+ 'Main': 'rgba(0,255,0,0.1)', # Green
240
+ 'Early': 'rgba(255,255,0,0.1)', # Yellow
241
+ 'Late': 'rgba(255,165,0,0.1)', # Orange
242
+ 'Dry': 'rgba(255,0,0,0.1)' # Red
243
+ }
244
+
245
+ for season in seasons:
246
+ season_data = df[df['season'] == season]
247
+ if not season_data.empty:
248
+ for row in range(1, 5):
249
+ fig.add_vrect(
250
+ x0=season_data['date'].iloc[0],
251
+ x1=season_data['date'].iloc[-1],
252
+ fillcolor=season_colors.get(season, 'rgba(128,128,128,0.1)'),
253
+ layer="below",
254
+ line_width=0,
255
+ annotation_text=season if row == 1 else None,
256
+ annotation_position="top left",
257
+ row=row, col=1
258
+ )
259
 
260
  def create_enhanced_map(self, lat, lon, score, ndvi_value):
261
+ """Create an interactive map with analysis overlays"""
262
  m = folium.Map(location=[lat, lon], zoom_start=13)
263
 
264
  # Add measurement tools