fnmrtns commited on
Commit
67d8d1b
·
verified ·
1 Parent(s): 8cfc18e

Upload visual3.py

Browse files
Files changed (1) hide show
  1. visual3.py +1806 -0
visual3.py ADDED
@@ -0,0 +1,1806 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import marimo
2
+
3
+ __generated_with = "0.23.1"
4
+ app = marimo.App(width="medium")
5
+
6
+
7
+ @app.cell
8
+ def _():
9
+ import marimo as mo
10
+ import pandas as pd
11
+ import numpy as np
12
+ from svg import SVG, Line, Path, G, Rect, Text
13
+ from sklearn.preprocessing import MinMaxScaler
14
+ import anywidget
15
+ import traitlets
16
+ # from scipy.stats import gaussian_kde
17
+ return G, Line, Path, Rect, SVG, Text, anywidget, mo, np, pd, traitlets
18
+
19
+
20
+ @app.cell
21
+ def _(pd):
22
+ shrubs = pd.read_excel("data/Coffee_structure_index_variables.xlsx")
23
+ c_yield = pd.read_excel("data/Coffee_yield.xlsx")
24
+ management = pd.read_excel("data/Environmental_and_management_variables.xlsx")
25
+ # merging shrub characteristics with yield of sites
26
+ shr_yield_first = pd.merge(shrubs, c_yield, on="Site ID", how="left")
27
+ shr_yield = shr_yield_first.merge(management[['Site ID', 'Coffee structure index']], on='Site ID', how='left')
28
+ return (shr_yield,)
29
+
30
+
31
+ @app.cell
32
+ def _(np, shr_yield):
33
+ # Adding for each shrub category based on fitted cluster of shrub & mean yield of its site
34
+ conditions_to_category = [
35
+ (shr_yield["Fitted cluster"] == 1) & (shr_yield["Mean_CC_Yield"] <= 1000),
36
+ (shr_yield["Fitted cluster"] == 2) & (shr_yield["Mean_CC_Yield"] <= 1000),
37
+ (shr_yield["Fitted cluster"] == 3) & (shr_yield["Mean_CC_Yield"] <= 1000),
38
+ (shr_yield["Fitted cluster"] == 1) & (shr_yield["Mean_CC_Yield"] > 1000),
39
+ (shr_yield["Fitted cluster"] == 2) & (shr_yield["Mean_CC_Yield"] > 1000),
40
+ (shr_yield["Fitted cluster"] == 3) & (shr_yield["Mean_CC_Yield"] > 1000)
41
+ ]
42
+
43
+ cat_names = ['1_low', '2_low', '3_low', "1_high", "2_high", "3_high"]
44
+
45
+ shr_yield['category'] = np.select(conditions_to_category, cat_names, default='other')
46
+ return
47
+
48
+
49
+ @app.cell
50
+ def _(shr_yield):
51
+ # aggregated values for shrubs in each category (median, quantiles)
52
+ _shr_num_cols = [
53
+ 'Primary orthotropic shoots',
54
+ 'Secondary orthotropic shoots',
55
+ 'Primary and secondary orthotropic shoots',
56
+ "Plagiotropic shoots",
57
+ "Proportion of coffee height with bearing shoots",
58
+ "Mean coffee canopy Diameter",
59
+ "Mean stem diameter at Knee Height",
60
+ ]
61
+
62
+ # function to aggregate quantiles 0.25 and 0.75:
63
+ def q25(_x): return _x.quantile(0.25)
64
+ def q75(_x): return _x.quantile(0.75)
65
+
66
+ # new df _agg_values
67
+ _agg_values = shr_yield.groupby('category')[_shr_num_cols].agg(['median', q25, q75])
68
+
69
+ # names for columns in _agg_values
70
+ _agg_values.columns = ['_'.join(col) for col in _agg_values.columns]
71
+ _agg_values = _agg_values.reset_index()
72
+
73
+ # shr_yield with _agg_values
74
+ shr_yield_std_agg = shr_yield.merge(_agg_values, on='category', how='left')
75
+
76
+ # df with median and quantiles 0.5, 0.75
77
+ _columns_vis_median_quant = ['category'] + [
78
+ col for col in _agg_values.columns
79
+ if any(x in col for x in ['_median', '_q25', '_q75']) and '_std' not in col
80
+ ]
81
+
82
+ shr_yield_gr_median_quant = shr_yield_std_agg[_columns_vis_median_quant].groupby('category').mean().reset_index()
83
+ return (shr_yield_gr_median_quant,)
84
+
85
+
86
+ @app.cell
87
+ def _(shr_yield_gr_median_quant):
88
+ # #USING: shr_yield_gr_median_quant as df and manual MINMAX scaling (minmaxscaler sklearn only per column, We need to scale median columns and quantile columns together)
89
+ shr_num_cols_for_minmax = [
90
+ 'Primary orthotropic shoots',
91
+ 'Secondary orthotropic shoots',
92
+ 'Plagiotropic shoots',
93
+ 'Proportion of coffee height with bearing shoots',
94
+ 'Mean coffee canopy Diameter',
95
+ 'Mean stem diameter at Knee Height'
96
+ ]
97
+
98
+ shr_yield_gr_median_quant_minmax = shr_yield_gr_median_quant.copy()
99
+
100
+ minmax_for_axis = {} # minmax_for_axis = to show the unscaled min and max median values as text on top/bottom of axis
101
+ for _col in shr_num_cols_for_minmax:
102
+ mincol = shr_yield_gr_median_quant[f'{_col}_median'].min() # MINMAX BASED ON MEDIAN
103
+ maxcol = shr_yield_gr_median_quant[f'{_col}_median'].max() # MINMAX BASED ON MEDIAN
104
+ minmax_for_axis[_col] = {"min": round(mincol, 1), "max": round(maxcol, 1)} # MINMAX BASED ON MEDIAN
105
+
106
+ # mincol = shr_yield_gr_median_quant[f'{_col}_q25'].min() # MINMAX BASED ON QUANTILES
107
+ # maxcol = shr_yield_gr_median_quant[f'{_col}_q75'].max() # MINMAX BASED ON QUANTILES
108
+ # minmax_for_axis[_col] = {"min": round(mincol, 1), "max": round(maxcol, 1)} # MINMAX BASED ON QUANTILES
109
+
110
+ for _suffix in ['_median', '_q25', '_q75']:
111
+ _scaled = (shr_yield_gr_median_quant[f'{_col}{_suffix}'] - mincol) / (maxcol - mincol)
112
+ shr_yield_gr_median_quant_minmax[f'{_col}{_suffix}_minmax'] = _scaled
113
+
114
+ # calculating global max and min for all colums to ensure sufficient lenght of y axis to show also quantile values outside 0,1 range
115
+ _median_q25_q75_minmax_cols = [
116
+ f'{_col}{_suffix}_minmax'
117
+ for _col in shr_num_cols_for_minmax
118
+ for _suffix in ['_median', '_q25', '_q75']
119
+ ]
120
+ global_min = shr_yield_gr_median_quant_minmax[_median_q25_q75_minmax_cols].min().min()
121
+ global_max = shr_yield_gr_median_quant_minmax[_median_q25_q75_minmax_cols].max().max()
122
+ return (
123
+ global_max,
124
+ global_min,
125
+ minmax_for_axis,
126
+ shr_num_cols_for_minmax,
127
+ shr_yield_gr_median_quant_minmax,
128
+ )
129
+
130
+
131
+ @app.cell
132
+ def _(shr_yield):
133
+ shr_num_cols_sites = [
134
+ 'Primary orthotropic shoots',
135
+ 'Secondary orthotropic shoots',
136
+ 'Plagiotropic shoots',
137
+ 'Proportion of coffee height with bearing shoots',
138
+ 'Mean coffee canopy Diameter',
139
+ 'Mean stem diameter at Knee Height'
140
+ ]
141
+
142
+ # no extra axes
143
+ # site_medians_1 = shr_yield.groupby('Site ID')[shr_num_cols_sites].median().reset_index()
144
+ # site_medians_2 = site_medians_1.merge(
145
+ # shr_yield[['Site ID', 'Coffee structure index']].drop_duplicates(),
146
+ # on='Site ID',
147
+ # how='left'
148
+ # )
149
+ # site_medians = site_medians_2.sort_values('Coffee structure index').reset_index(drop=True)
150
+
151
+ ## EXTRA AXES
152
+ shr_num_cols_sites_extra = [
153
+ 'Mean_CC_Yield',
154
+ 'CC_Yield_2018',
155
+ 'CC_Yield_2017_2019_mean',
156
+ 'Coffee structure index'
157
+ ]
158
+
159
+ _cols_for_merge = [
160
+ 'Mean_CC_Yield',
161
+ 'CC_Yield_2017',
162
+ 'CC_Yield_2018',
163
+ 'CC_Yield_2019',
164
+ 'Coffee structure index'
165
+ ]
166
+
167
+ site_medians_1 = shr_yield.groupby('Site ID')[shr_num_cols_sites].median().reset_index()
168
+ site_medians_2 = site_medians_1.merge(
169
+ shr_yield[['Site ID'] + _cols_for_merge].drop_duplicates('Site ID'),
170
+ on='Site ID',
171
+ how='left'
172
+ )
173
+ site_medians = site_medians_2.sort_values('Coffee structure index').reset_index(drop=True)
174
+ site_medians['CC_Yield_2017_2019_mean'] = (site_medians['CC_Yield_2017'] + site_medians['CC_Yield_2019']) / 2
175
+ return shr_num_cols_sites_extra, site_medians
176
+
177
+
178
+ @app.cell
179
+ def _(shr_num_cols_sites_extra, site_medians):
180
+ ##SCALING FOR EXTRA AXES
181
+ # minmax schaling voor extra assen
182
+ minmax_extra = {}
183
+
184
+ # yield kolommen: geschaald op Mean_CC_Yield min/max
185
+ _yield_min = site_medians['Mean_CC_Yield'].min()
186
+ _yield_max = site_medians['Mean_CC_Yield'].max()
187
+ minmax_extra['Mean_CC_Yield'] = {"min": round(_yield_min, 1), "max": round(_yield_max, 1), "scale_min": _yield_min, "scale_max": _yield_max}
188
+ minmax_extra['CC_Yield_2018'] = {"min": round(_yield_min, 1), "max": round(_yield_max, 1), "scale_min": _yield_min, "scale_max": _yield_max}
189
+ minmax_extra['CC_Yield_2017_2019_mean'] = {"min": round(_yield_min, 1), "max": round(_yield_max, 1), "scale_min": _yield_min, "scale_max": _yield_max}
190
+
191
+ # structure index: eigen min/max
192
+ _si_min = site_medians['Coffee structure index'].min()
193
+ _si_max = site_medians['Coffee structure index'].max()
194
+ minmax_extra['Coffee structure index'] = {"min": round(_si_min, 2), "max": round(_si_max, 2), "scale_min": _si_min, "scale_max": _si_max}
195
+
196
+ # geschaalde waarden per site per extra variabele
197
+ for _col in shr_num_cols_sites_extra:
198
+ _smin = minmax_extra[_col]["scale_min"]
199
+ _smax = minmax_extra[_col]["scale_max"]
200
+ site_medians[f'{_col}_minmax'] = (site_medians[_col] - _smin) / (_smax - _smin)
201
+ return (minmax_extra,)
202
+
203
+
204
+ @app.cell
205
+ def _():
206
+ # KDE NOT USED - HISTOGRAMS INSTEAD
207
+ # calculating density curves for plotting under y axis per variable (real values, over all entities)
208
+ # # with Kernel Density Estimation (KDE)
209
+
210
+
211
+ # kde_data = {}
212
+ # for _col in kde_cols:
213
+ # _vals = shr_yield[_col].dropna().values
214
+ # _kde = gaussian_kde(_vals, bw_method=0.05)
215
+ # _x_min = _vals.min()
216
+ # _x_max = _vals.max()
217
+ # _x_range = np.linspace(_x_min, _x_max, 200)
218
+ # _density = _kde(_x_range)
219
+ # kde_data[_col] = {
220
+ # "x_min": _x_min,
221
+ # "x_max": _x_max,
222
+ # "x_range": _x_range,
223
+ # "density": _density,
224
+ # "density_max": _density.max()
225
+ # }
226
+ return
227
+
228
+
229
+ @app.cell
230
+ def _(np, shr_yield):
231
+ # calculating histograms (miniature distribution per shrub variable)
232
+ hist_cols = [
233
+ 'Primary orthotropic shoots',
234
+ 'Secondary orthotropic shoots',
235
+ 'Plagiotropic shoots',
236
+ 'Proportion of coffee height with bearing shoots',
237
+ 'Mean coffee canopy Diameter',
238
+ 'Mean stem diameter at Knee Height'
239
+ ]
240
+
241
+ hist_data = {}
242
+ for _col in hist_cols:
243
+ _vals = shr_yield[_col].dropna().values
244
+ _counts, _bin_edges = np.histogram(_vals, bins=50)
245
+ hist_data[_col] = {
246
+ "x_min": _bin_edges[0],
247
+ "x_max": _bin_edges[-1],
248
+ "counts": _counts,
249
+ "bin_edges": _bin_edges,
250
+ "counts_max": _counts.max()
251
+ }
252
+ return hist_cols, hist_data
253
+
254
+
255
+ @app.cell
256
+ def _():
257
+ # defining width and height of svg's
258
+ svg_width = 1400 # if minmax based on quantiles: 1600 OR else 1600
259
+ svg_height = 500 # if minmax based on quantiles: 800 OR else 600
260
+
261
+ # extra space for legend
262
+ #svg_legend_width = 250
263
+ return svg_height, svg_width
264
+
265
+
266
+ @app.function
267
+ # function rescale
268
+ def rescale(_yvalue, domain_min, domain_max, range_min, range_max):
269
+ scale = (range_max - range_min) / (domain_max - domain_min)
270
+ return range_min + (_yvalue - domain_min) * scale
271
+
272
+
273
+ @app.cell
274
+ def _():
275
+ # creation of get_class function to allocate class to Paths
276
+ _class_mapping = {
277
+ "1_low": "low_1",
278
+ "1_high": "high_1",
279
+ "2_low": "low_2",
280
+ "2_high": "high_2",
281
+ "3_low": "low_3",
282
+ "3_high": "high_3"
283
+ }
284
+ def get_class(_category_value):
285
+ return _class_mapping[_category_value]
286
+
287
+ return (get_class,)
288
+
289
+
290
+ @app.cell
291
+ def _(svg_width):
292
+ # creating x values:
293
+ _left_margin = 100 # leaving a margin at the edge besides the y axis
294
+ _right_margin = 100
295
+ x_values = []
296
+ for _i in range(0, 6):
297
+ _x_i = _left_margin + (svg_width - _left_margin - _right_margin) / 5 * _i
298
+ x_values.append(_x_i)
299
+ return (x_values,)
300
+
301
+
302
+ @app.cell
303
+ def _(x_values):
304
+ ## EXTRA AXES
305
+ # extra x values for new 4 axes
306
+ _x_step = (x_values[-1] - x_values[0]) / 10
307
+ _extra_offset = 100
308
+ x_values_extra = [x_values[-1] + _extra_offset + _x_step * (_i + 1) for _i in range(4)]
309
+ x_values_all = x_values + x_values_extra
310
+ ## END EXTRA AXES
311
+ return x_values_all, x_values_extra
312
+
313
+
314
+ @app.cell
315
+ def _(
316
+ G,
317
+ Line,
318
+ Path,
319
+ Rect,
320
+ SVG,
321
+ Text,
322
+ get_class,
323
+ global_max,
324
+ global_min,
325
+ hist_cols,
326
+ hist_data,
327
+ minmax_extra,
328
+ minmax_for_axis,
329
+ np,
330
+ shr_num_cols_for_minmax,
331
+ shr_num_cols_sites_extra,
332
+ shr_yield,
333
+ shr_yield_gr_median_quant,
334
+ shr_yield_gr_median_quant_minmax,
335
+ site_medians,
336
+ svg_height,
337
+ svg_width,
338
+ x_values,
339
+ x_values_all,
340
+ x_values_extra,
341
+ ):
342
+ ## WITH MINMAX sCALING
343
+ # defining axis labels (top of axis, vertically, split after every word)
344
+ _axis_labels = [
345
+ "Nr of\nPrimary\northotropic\nshoots",
346
+ "Nr of\nSecondary\northotropic\nshoots",
347
+ "Nr of\nPlagiotropic\nshoots",
348
+ "Proportion\nof tree with\nfruit bearing\nshoots",
349
+ "Mean\nCanopy\ndiameter",
350
+ "Mean\nStem\ndiameter"
351
+ ]
352
+
353
+ ## EXTRA AXES
354
+ _extra_axis_labels = [
355
+ "Mean\nYield",
356
+ "Yield\n2018",
357
+ "Mean Yield\n2017 & 2019",
358
+ "Coffee\nStructure\nIndex"
359
+ ]
360
+ ##
361
+
362
+ # adapting _top_margin formerly created to the lenght of longest label
363
+ _top_margin = max(len(_label.split("\n")) for _label in _axis_labels) * 14 + 40
364
+
365
+ # adding padding, to give some margin at edge of SVG
366
+ _padding = 5
367
+
368
+ # adding _bottom_margin
369
+ _bottom_margin = 20
370
+
371
+ # adding title maring
372
+ _title_margin = 60
373
+
374
+ # pixel height of plot
375
+ y_val1 = _top_margin
376
+ y_val0 = svg_height - _padding
377
+ _plot_pixel_height = y_val0 - y_val1
378
+
379
+ # calculating extra space on y axis to show also quantile values outside 0,1 range (based on global_max and global_min)
380
+ _extra_top = (global_max - 1) * _plot_pixel_height
381
+ _extra_bottom = abs(min(0, global_min)) * _plot_pixel_height
382
+
383
+ # calculating actual pixel top and pixel bottom of plot
384
+ _y_top = y_val1 - _extra_top
385
+ _y_bot = y_val0 + _extra_bottom
386
+
387
+ # if _y_top = negative => shift all down
388
+ _margin = 300 # MINMAX QUANTILES = 80 else 150
389
+ _y_offset = max(0, -_y_top) + _margin + _title_margin
390
+ _y_top = _y_top + _y_offset
391
+ _y_bot = _y_bot + _y_offset
392
+ y_val0 = y_val0 + _y_offset
393
+ y_val1 = y_val1 + _y_offset
394
+
395
+ # creating _label_elements = y axis labels
396
+ _label_elements = []
397
+ for _x, _label in zip(x_values, _axis_labels):
398
+ _words = _label.split("\n")
399
+ for _idx, _word in enumerate(_words):
400
+ _label_elements.append(
401
+ Text(
402
+ x=_x + _idx * 12 + 50,
403
+ y=_y_top - 40,
404
+ text=_word,
405
+ font_size=10,
406
+ text_anchor="start",
407
+ transform=f"rotate(-90, {_x + _idx * 12 + 15}, {_y_top - 10})",
408
+ class_="axis_label"
409
+ )
410
+ )
411
+
412
+
413
+ # selecting columns for creation of _y_values (_minmax median values) (prim+sec orthotrop not incl)
414
+ _cols_median = [
415
+ col for col in shr_yield_gr_median_quant_minmax.columns
416
+ if '_median' in col and "_minmax" in col and "Primary and secondary orthotropic shoots" not in col
417
+ ]
418
+
419
+ # selecting columns for creation of quantile lines 0.25 and 0.75
420
+ _cols_q25 = [
421
+ col for col in shr_yield_gr_median_quant_minmax.columns
422
+ if '_q25' in col and "_minmax" in col and "Primary and secondary orthotropic shoots" not in col
423
+ ]
424
+ _cols_q75 = [
425
+ col for col in shr_yield_gr_median_quant_minmax.columns
426
+ if '_q75' in col and "_minmax" in col and "Primary and secondary orthotropic shoots" not in col
427
+ ]
428
+
429
+ # function to create Paths and quantile lines and group them in group per category
430
+ def _create_path(_row):
431
+ _class = get_class(_row["category"])
432
+
433
+ _fill_colors = {
434
+ "low_1": "#b8c8f5", "high_1": "#2d46dc",
435
+ "low_2": "#c8f0a0", "high_2": "#91d76e",
436
+ "low_3": "#f0a0a2", "high_3": "#be2d32"
437
+ }
438
+
439
+ # median
440
+ _y_median = [rescale(v, 0, 1, y_val0, y_val1) for v in _row[_cols_median].tolist()]
441
+ _d_median = f"M {x_values[0]},{_y_median[0]} " + \
442
+ " ".join(f"L {_x},{_y}" for _x, _y in zip(x_values[1:], _y_median[1:]))
443
+
444
+ # q25 line and q75 line and filled area in between
445
+ _y_q25 = [rescale(v, 0, 1, y_val0, y_val1) for v in _row[_cols_q25].tolist()]
446
+ _y_q75 = [rescale(v, 0, 1, y_val0, y_val1) for v in _row[_cols_q75].tolist()]
447
+ _d_area = (
448
+ f"M {x_values[0]},{_y_q75[0]} " +
449
+ " ".join(f"L {_x},{_y}" for _x, _y in zip(x_values[1:], _y_q75[1:])) +
450
+ f" L {x_values[-1]},{_y_q25[-1]} " +
451
+ " ".join(f"L {_x},{_y}" for _x, _y in zip(reversed(x_values[:-1]), reversed(_y_q25[:-1]))) +
452
+ " Z"
453
+ )
454
+
455
+ # QUANTILE LABELS WITH HOVER
456
+ _qlabel_elements = []
457
+ for _x, _col, _yq25, _yq75 in zip(x_values, shr_num_cols_for_minmax, _y_q25, _y_q75):
458
+ _val_q25_display = round(_row[f'{_col}_q25'], 1)
459
+ _val_q75_display = round(_row[f'{_col}_q75'], 1)
460
+
461
+ _qlabel_elements.append(
462
+ Text(
463
+ x=_x + 5,
464
+ y=_yq25 + 10,
465
+ text=str(_val_q25_display),
466
+ font_size=10,
467
+ class_=f"quantile_label {_class}"
468
+ )
469
+ )
470
+ _qlabel_elements.append(
471
+ Text(
472
+ x=_x + 5,
473
+ y=_yq75 - 3,
474
+ text=str(_val_q75_display),
475
+ font_size=10,
476
+ class_=f"quantile_label {_class}"
477
+ )
478
+ )
479
+
480
+ return G(
481
+ id=str(_row["category"]),
482
+ elements=[
483
+ Path(d=_d_area, class_=f"{_class} quantile_area", style=f"fill:{_fill_colors[_class]};opacity:0;stroke:none;"),
484
+ Path(d=_d_median, class_=_class)
485
+ ] + _qlabel_elements
486
+ )
487
+
488
+ # creating path elements ( median, q25, q75)
489
+ _path_elements_minmax = []
490
+ for _, _row in shr_yield_gr_median_quant_minmax.iterrows():
491
+ _path_elements_minmax.append(_create_path(_row))
492
+
493
+ # creating site median paths (grey background lines)
494
+ _site_elements = []
495
+ for _, _row in site_medians.iterrows():
496
+ _site_id = str(_row['Site ID'])
497
+ _cat = shr_yield[shr_yield['Site ID'] == _row['Site ID']]['category'].iloc[0]
498
+
499
+ _y_values = []
500
+ for _col in shr_num_cols_for_minmax:
501
+ _mincol = shr_yield_gr_median_quant[f'{_col}_median'].min()
502
+ _maxcol = shr_yield_gr_median_quant[f'{_col}_median'].max()
503
+ _scaled = (_row[_col] - _mincol) / (_maxcol - _mincol)
504
+ _y_values.append(rescale(_scaled, 0, 1, y_val0, y_val1))
505
+
506
+ ## EXTRA AXES
507
+ _y_values_extra = []
508
+ for _col in shr_num_cols_sites_extra:
509
+ _scaled = _row[f'{_col}_minmax']
510
+ _y_values_extra.append(rescale(_scaled, 0, 1, y_val0, y_val1))
511
+
512
+ _y_values_all = _y_values + _y_values_extra
513
+
514
+ _d_site = f"M {x_values_all[0]},{_y_values_all[0]} " + \
515
+ " ".join(f"L {_x},{_y}" for _x, _y in zip(x_values_all[1:], _y_values_all[1:]))
516
+
517
+ ## NO EXTRA AXES
518
+ # _d_site = f"M {x_values[0]},{_y_values[0]} " + \
519
+ # " ".join(f"L {_x},{_y}" for _x, _y in zip(x_values[1:], _y_values[1:]))
520
+
521
+ _site_class = "site_line_high" if "high" in _cat else "site_line_low"
522
+ _site_elements.append(
523
+ Path(
524
+ d=_d_site,
525
+ id=f"site_{_site_id}",
526
+ class_=_site_class,
527
+ )
528
+ )
529
+
530
+ # creating grid lines
531
+ _grid_start = np.floor(global_min / 0.25) * 0.25
532
+ _grid_end = np.ceil(global_max / 0.25) * 0.25
533
+ _gridlines_values = np.arange(_grid_start, _grid_end + 0.25, 0.25).tolist()
534
+
535
+ _grid_elements_minmax = []
536
+ for _i in _gridlines_values:
537
+ _y = rescale(_i, 0, 1, y_val0, y_val1)
538
+ if _y >= _y_top:
539
+ _grid_elements_minmax.append(
540
+ Line(
541
+ x1=x_values[0],
542
+ y1=_y,
543
+ x2=x_values[-1],
544
+ y2=_y,
545
+ class_="gridline"
546
+ )
547
+ )
548
+
549
+ # creating black dashed gridlines for minmax 0 and 1 values
550
+ for _x in x_values:
551
+ _y1 = rescale(1, 0, 1, y_val0, y_val1)
552
+ _grid_elements_minmax.append(
553
+ Line(
554
+ x1=x_values[0] - 30,
555
+ y1=_y1,
556
+ x2=x_values[-1],
557
+ y2=_y1,
558
+ class_="gridline_minmax_01"
559
+ )
560
+ )
561
+ _y0 = rescale(0, 0, 1, y_val0, y_val1)
562
+ _grid_elements_minmax.append(
563
+ Line(
564
+ x1=x_values[0] - 30,
565
+ y1=_y0,
566
+ x2=x_values[-1],
567
+ y2=_y0,
568
+ class_="gridline_minmax_01"
569
+ )
570
+ )
571
+ break # to only execute once, so not for all gridlines but only 0 1 minmax values
572
+
573
+ ## EXTRA AXES
574
+ # creating black dashed gridlines 0 and 1 for extra axes section
575
+ _y1_extra = rescale(1, 0, 1, y_val0, y_val1)
576
+ _y0_extra = rescale(0, 0, 1, y_val0, y_val1)
577
+ _grid_elements_minmax.append(
578
+ Line(
579
+ x1=x_values_extra[0],
580
+ y1=_y1_extra,
581
+ x2=x_values_extra[-1],
582
+ y2=_y1_extra,
583
+ class_="gridline_minmax_01"
584
+ )
585
+ )
586
+ _grid_elements_minmax.append(
587
+ Line(
588
+ x1=x_values_extra[0],
589
+ y1=_y0_extra,
590
+ x2=x_values_extra[-1],
591
+ y2=_y0_extra,
592
+ class_="gridline_minmax_01"
593
+ )
594
+ )
595
+ ###
596
+
597
+ # creating axis
598
+ _axis_elements = []
599
+ _extra_lenght_y_axis_ontop = 30
600
+ for _i in x_values:
601
+ _axis_elements.append(
602
+ Line(
603
+ x1=_i,
604
+ y1=_y_top - _extra_lenght_y_axis_ontop,
605
+ x2=_i,
606
+ y2=_y_bot + _extra_lenght_y_axis_ontop,
607
+ class_="axis"
608
+ )
609
+ )
610
+
611
+ # creating axis heads (arrows on top)
612
+ _arrow_elements = []
613
+ for _i in x_values:
614
+ _arrow_elements.append(
615
+ Line(x1=_i - 5, y1=_y_top - 18, x2=_i, y2=_y_top - _extra_lenght_y_axis_ontop, class_="arrow")
616
+ )
617
+ _arrow_elements.append(
618
+ Line(x1=_i + 5, y1=_y_top - 18, x2=_i, y2=_y_top - _extra_lenght_y_axis_ontop, class_="arrow")
619
+ )
620
+
621
+ ## EXTRA AXES - creating extra axes
622
+ for _i in x_values_extra:
623
+ _axis_elements.append(
624
+ Line(
625
+ x1=_i,
626
+ y1=_y_top - _extra_lenght_y_axis_ontop,
627
+ x2=_i,
628
+ y2=_y_bot + _extra_lenght_y_axis_ontop,
629
+ class_="axis"
630
+ )
631
+ )
632
+ _arrow_elements.append(
633
+ Line(x1=_i - 5, y1=_y_top - 18, x2=_i, y2=_y_top - _extra_lenght_y_axis_ontop, class_="arrow")
634
+ )
635
+ _arrow_elements.append(
636
+ Line(x1=_i + 5, y1=_y_top - 18, x2=_i, y2=_y_top - _extra_lenght_y_axis_ontop, class_="arrow")
637
+ )
638
+
639
+ # creating fixed min and max median values on y axis (real median values displayed, not minmax transformed)
640
+ _rv_label_elements = []
641
+ for _x, _col in zip(x_values, shr_num_cols_for_minmax):
642
+
643
+ # definig min and max median values
644
+ _max_val = shr_yield_gr_median_quant_minmax[f'{_col}_median_minmax'].max() # MINMAX BASED ON MEDIAN
645
+ _min_val = shr_yield_gr_median_quant_minmax[f'{_col}_median_minmax'].min() # MINMAX BASED ON MEDIAN
646
+
647
+ # calculating position on y axis
648
+
649
+ _y_max = rescale(_max_val, 0, 1, y_val0, y_val1) # MINMAX BASED ON MEDIAN
650
+ _y_min = rescale(_min_val, 0, 1, y_val0, y_val1) # MINMAX BASED ON MEDIAN
651
+
652
+ # _y_max = rescale(1, 0, 1, y_val0, y_val1) # MINMAX BASED ON QUANTILES
653
+ # _y_min = rescale(0, 0, 1, y_val0, y_val1) # MINMAX BASED ON QUANTILES
654
+
655
+ _rv_label_elements.append(
656
+ Text(
657
+ x=_x + 5,
658
+ y=_y_max - 10,
659
+ text=str(minmax_for_axis[_col]["max"]),
660
+ font_size=9,
661
+ class_="axis_rv_label"
662
+ )
663
+ )
664
+ _rv_label_elements.append(
665
+ Text(
666
+ x=_x + 5,
667
+ y=_y_min - 10,
668
+ text=str(minmax_for_axis[_col]["min"]),
669
+ font_size=9,
670
+ class_="axis_rv_label"
671
+ )
672
+ )
673
+
674
+ _rv_label_elements.append(
675
+ Text(
676
+ x=_x + 5,
677
+ y=rescale(0.5, 0, 1, y_val0, y_val1) - 10,
678
+ text=str(round(minmax_for_axis[_col]["min"] + 0.5 * \
679
+ (minmax_for_axis[_col]["max"] - minmax_for_axis[_col]["min"]), 1)),
680
+ font_size=9,
681
+ class_="axis_rv_label"
682
+ )
683
+ )
684
+
685
+ # # creating fixed middle y axis values - NOT KEPT
686
+ # _mid_val_display = round((minmax_for_axis[_col]["min"] + minmax_for_axis[_col]["max"]) / 2, 1)
687
+ # _y_mid = rescale(0.5, 0, 1, y_val0, y_val1)
688
+
689
+ # _minmax_label_elements.append(
690
+ # Text(
691
+ # x=_x + 5,
692
+ # y=_y_mid + 4,
693
+ # text=str(_mid_val_display),
694
+ # font_size=9,
695
+ # class_="axis_minmax_label"
696
+ # )
697
+ # )
698
+
699
+ # extra gridlines: 0.25, 0.5, 0.75 and value above [0,1]
700
+ # extra _minmax_label_elements as gridline (on under gridline only showing for 4th y axis as other values would be
701
+ # negative or non-informative)
702
+ _extra_gridlines = [_i for _i in _gridlines_values if _i not in [0, 1, 0.25, 0.75, -0.25, -0.75, 1.25, 0.5, 1.75]]
703
+ for _i in _extra_gridlines:
704
+ _real_val = round(
705
+ minmax_for_axis[_col]["min"] + _i * (minmax_for_axis[_col]["max"] - minmax_for_axis[_col]["min"]),
706
+ 1
707
+ )
708
+ _y = rescale(_i, 0, 1, y_val0, y_val1)
709
+ if _real_val > 2:
710
+ _rv_label_elements.append(
711
+ Text(
712
+ x=_x + 5,
713
+ y=_y + 10,
714
+ text=str(_real_val),
715
+ font_size=9,
716
+ class_="axis_rv_label")
717
+ )
718
+
719
+
720
+ # minmax 0 en 1 labels, accompanying minmax 0 and 1 dash line
721
+ for _x in x_values:
722
+ _y1 = rescale(1, 0, 1, y_val0, y_val1)
723
+ _y0 = rescale(0, 0, 1, y_val0, y_val1)
724
+
725
+ _rv_label_elements.append(
726
+ Text(
727
+ x=_x - 15,
728
+ y=_y1 + 10,
729
+ text="MinMax 1",
730
+ font_size=8,
731
+ text_anchor="end",
732
+ class_="minmax_01_labels"
733
+ )
734
+ )
735
+ _rv_label_elements.append(
736
+ Text(
737
+ x=_x - 15,
738
+ y=_y0 + 10,
739
+ text="MinMax 0",
740
+ font_size=8,
741
+ text_anchor="end",
742
+ class_="minmax_01_labels"
743
+ )
744
+ )
745
+ break # to only execute once, for the first y axis, not for the others
746
+
747
+
748
+ ##EXTRA AXES - creating axes labels and rv labels
749
+ for _x, _col, _label in zip(x_values_extra, shr_num_cols_sites_extra, _extra_axis_labels):
750
+
751
+ # extra axes labels
752
+ _words = _label.split("\n")
753
+ for _idx, _word in enumerate(_words):
754
+ _label_elements.append(
755
+ Text(
756
+ x=_x + _idx * 12 + 30,
757
+ y=_y_top - 60,
758
+ text=_word,
759
+ font_size=10,
760
+ text_anchor="start",
761
+ transform=f"rotate(-90, {_x + _idx * 12 + 15}, {_y_top - 30})",
762
+ class_="axis_label"
763
+ )
764
+ )
765
+
766
+ # extra axes min max rv labels
767
+ _real_min = minmax_extra[_col]["min"]
768
+ _real_max = minmax_extra[_col]["max"]
769
+ _real_mid = round(_real_min + 0.5 * (_real_max - _real_min), 1)
770
+
771
+ _rv_label_elements.append(
772
+ Text(x=_x + 5, y=rescale(1, 0, 1, y_val0, y_val1) - 10,
773
+ text=str(_real_max), font_size=9, class_="axis_rv_label")
774
+ )
775
+ _rv_label_elements.append(
776
+ Text(x=_x + 5, y=rescale(0, 0, 1, y_val0, y_val1) - 10,
777
+ text=str(_real_min), font_size=9, class_="axis_rv_label")
778
+ )
779
+ _rv_label_elements.append(
780
+ Text(x=_x + 5, y=rescale(0.5, 0, 1, y_val0, y_val1) - 10,
781
+ text=str(_real_mid), font_size=9, class_="axis_rv_label")
782
+ )
783
+ ##
784
+
785
+
786
+ # tick elements for gridline labels on y axis
787
+ _tick_elements = []
788
+ for _i in [0, 0.5, 1,
789
+ 1.5, # MINMAX MEDIAN else comment
790
+ ]:
791
+ _y = rescale(_i, 0, 1, y_val0, y_val1)
792
+ if _y >= _y_top:
793
+ for _x in x_values:
794
+ _tick_elements.append(
795
+ Line(
796
+ x1=_x - 4,
797
+ y1=_y,
798
+ x2=_x + 4,
799
+ y2=_y,
800
+ class_="axis"
801
+ )
802
+ )
803
+
804
+
805
+ # extra tick element for 4th axis under extra gridline
806
+ _tick_elements.append(
807
+ Line(
808
+ x1= x_values[3] - 4,
809
+ y1= rescale(-0.5, 0, 1, y_val0, y_val1),
810
+ x2= x_values[3] + 4,
811
+ y2= rescale(-0.5, 0, 1, y_val0, y_val1),
812
+ class_="axis"
813
+ )
814
+ )
815
+
816
+ ## EXTRA AXES - ticks for extra axes
817
+ for _i in [0, 0.5, 1, 1.5]:
818
+ _y = rescale(_i, 0, 1, y_val0, y_val1)
819
+ if _y >= _y_top:
820
+ for _x in x_values_extra:
821
+ _tick_elements.append(
822
+ Line(
823
+ x1=_x - 4,
824
+ y1=_y,
825
+ x2=_x + 4,
826
+ y2=_y,
827
+ class_="axis"
828
+ )
829
+ )
830
+
831
+ # creating median labels, shown when checkbox is ticked via anywidget
832
+ _median_label_elements = []
833
+ for _, _row in shr_yield_gr_median_quant_minmax.iterrows():
834
+ _class = get_class(_row["category"])
835
+ for _x, _col in zip(x_values, shr_num_cols_for_minmax):
836
+ _val_minmax = _row[f'{_col}_median_minmax']
837
+ _val_display = round(_row[f'{_col}_median'], 1)
838
+ _y = rescale(_val_minmax, 0, 1, y_val0, y_val1)
839
+
840
+ _median_label_elements.append(
841
+ Text(
842
+ x=_x - 35,
843
+ y=_y - 15,
844
+ text=str(_val_display),
845
+ font_size=11,
846
+ class_=f"median_label {_class} median_label_{_row['category']}",
847
+ )
848
+ )
849
+
850
+ # creation of histogram elements (rug old name from former rug_plot)
851
+ _rug_strip_top = _y_bot + 120
852
+ _rug_strip_height = 40
853
+ _offset_rug = 30
854
+
855
+ _rug_elements = []
856
+ for _x, _col in zip(x_values, hist_cols):
857
+ _d = hist_data[_col]
858
+ _half_width = 60
859
+
860
+ # baseline
861
+ _rug_elements.append(
862
+ Line(
863
+ x1=_x - _half_width + _offset_rug,
864
+ y1=_rug_strip_top + _rug_strip_height,
865
+ x2=_x + _half_width + _offset_rug,
866
+ y2=_rug_strip_top + _rug_strip_height,
867
+ class_="rug_axis"
868
+ )
869
+ )
870
+
871
+ # mini x as
872
+ _rug_elements.append(
873
+ Line(
874
+ x1=_x - _half_width + _offset_rug,
875
+ y1=_rug_strip_top,
876
+ x2=_x - _half_width + _offset_rug,
877
+ y2=_rug_strip_top + _rug_strip_height,
878
+ class_="rug_axis"
879
+ )
880
+ )
881
+
882
+ # histogram bins
883
+ for _i in range(len(_d["counts"])):
884
+ _x_left = _x + (_d["bin_edges"][_i] - _d["x_min"]) / (_d["x_max"] - _d["x_min"]) * 2 * _half_width - _half_width + _offset_rug
885
+ _x_right = _x + (_d["bin_edges"][_i+1] - _d["x_min"]) / (_d["x_max"] - _d["x_min"]) * 2 * _half_width - _half_width + _offset_rug
886
+ _bar_height = (_d["counts"][_i] / _d["counts_max"]) * _rug_strip_height
887
+ _y_top_bar = _rug_strip_top + _rug_strip_height - _bar_height
888
+
889
+ if _d["counts"][_i] > 0:
890
+ _rug_elements.append(
891
+ Path(
892
+ d=f"M {_x_left},{_rug_strip_top + _rug_strip_height} " +
893
+ f"L {_x_left},{_y_top_bar} " +
894
+ f"L {_x_right},{_y_top_bar} " +
895
+ f"L {_x_right},{_rug_strip_top + _rug_strip_height} Z",
896
+ class_="hist_plot"
897
+ )
898
+ )
899
+
900
+ # histogram title
901
+ _rug_elements.append(
902
+ Text(
903
+ x=svg_width / 5,
904
+ y=_rug_strip_top - 40,
905
+ text="Distribution of raw observed values over all categories per variable",
906
+ font_size=9,
907
+ text_anchor="middle",
908
+ class_="hist_title"
909
+ )
910
+ )
911
+
912
+
913
+ # creating legend (used in JS)
914
+ legend_items = [
915
+ ("low_1", "#8fa8ee", 1, "Cluster 1 - low yield"), # light blue
916
+ ("high_1", "#2d46dc", 4, "Cluster 1 - high yield"), # dark blue
917
+ ("low_2", "#c8eaaa", 1, "Cluster 2 - low yield"), # light green
918
+ ("high_2", "#91d76e", 4, "Cluster 2 - high yield"), # dark green
919
+ ("low_3", "#e88a8d", 1, "Cluster 3 - low yield"), # light red
920
+ ("high_3", "#be2d32", 4, "Cluster 3 - high yield"), # dark red
921
+ ]
922
+
923
+ ## LEGEND NOT USED HERE - IMPLEMENTED VIA ANYWIDGET SO CAN BE POSITIONED OUTSIDE SVG FRAME
924
+ # _legend_elements = []
925
+ # for _idx, (_id, _color, _width, _label) in enumerate(legend_items):
926
+ # _y_pos = 20 + _idx * 30
927
+ # _legend_elements.append(
928
+ # G(
929
+ # id=_id,
930
+ # elements=[
931
+ # Line(
932
+ # x1=0, y1=0,
933
+ # x2=30, y2=0,
934
+ # stroke=_color,
935
+ # stroke_width=_width
936
+ # ),
937
+ # Text(
938
+ # x=40, y=5,
939
+ # text=_label,
940
+ # font_size=11
941
+ # )
942
+ # ],
943
+ # transform=f"translate(0, {_y_pos})"
944
+ # )
945
+ # )
946
+
947
+ # _legend_group = G(
948
+ # elements=_legend_elements,
949
+ # transform=f"translate({svg_width + 40}, {_top_margin})" # position legend: right side of visual, height of plot
950
+ # )
951
+
952
+ # creating title above plot
953
+ _title = Text(
954
+ x=svg_width / 2,
955
+ y=_title_margin/2,
956
+ text="Shrub profiles by shrub's individual management cluster x site's yield class",
957
+ font_size= 20,
958
+ text_anchor="middle",
959
+ class_="plot_title"
960
+ )
961
+
962
+ # creating subtitles above plot
963
+ _subtitle = Text(
964
+ x=svg_width / 2,
965
+ y=_title_margin/2 + 22,
966
+ text="Shrub profile for 6 categories: shrub's individual management cluster (1, 2 or 3) x site's yield class (low, high)",
967
+ font_size=13,
968
+ text_anchor="middle",
969
+ class_="plot_subtitle"
970
+ )
971
+
972
+ _subtitle2 = Text(
973
+ x=svg_width / 2,
974
+ y=_title_margin/2 + 44,
975
+ text="Median values per category, with 0.25 and 0.75 quantiles, MinMax scaled (0,1) on median category values per variable",
976
+ font_size=13,
977
+ text_anchor="middle",
978
+ class_="plot_subtitle"
979
+ )
980
+
981
+ ## EXTRA AXES - FILL BEHIND EXTRA AXES
982
+ _extra_bg = Rect(
983
+ x=x_values_extra[0] - 50,
984
+ y=_y_top - 160,
985
+ width=x_values_extra[-1] - x_values_extra[0] + 100,
986
+ height=_y_bot - _y_top + 200,
987
+ style="fill:#f5f5f5;stroke:#ccc;stroke-width:1;"
988
+ )
989
+
990
+ # showing SVG
991
+ svg_minmax = SVG(
992
+ #width=svg_width, ## NO EXTRA AXES
993
+ #+ svg_legend_width,
994
+ width=x_values_extra[-1] + 150, ## EXTRA AXES
995
+ height = _rug_strip_top + _rug_strip_height + _bottom_margin,
996
+ class_="fien_notebook",
997
+ elements=[_title, _subtitle, _subtitle2] + [_extra_bg] + _grid_elements_minmax + _axis_elements + _tick_elements + _arrow_elements + _label_elements + \
998
+ _rv_label_elements + _median_label_elements + _site_elements + _path_elements_minmax + _rug_elements # +[_legend_group]
999
+ )
1000
+ return legend_items, svg_minmax, y_val0, y_val1
1001
+
1002
+
1003
+ @app.cell
1004
+ def _(
1005
+ anywidget,
1006
+ get_class,
1007
+ legend_items,
1008
+ minmax_for_axis,
1009
+ mo,
1010
+ shr_num_cols_for_minmax,
1011
+ shr_yield,
1012
+ shr_yield_gr_median_quant_minmax,
1013
+ site_medians,
1014
+ svg_minmax,
1015
+ traitlets,
1016
+ y_val0,
1017
+ y_val1,
1018
+ ):
1019
+ # median values per categorie (unscaled + minmax for y position)
1020
+ _colors = {
1021
+ "1_low": legend_items[0][1],
1022
+ "1_high": legend_items[1][1],
1023
+ "2_low": legend_items[2][1],
1024
+ "2_high": legend_items[3][1],
1025
+ "3_low": legend_items[4][1],
1026
+ "3_high": legend_items[5][1],
1027
+ }
1028
+
1029
+ # site categories
1030
+ _site_data = {
1031
+ str(_row['Site ID']): {
1032
+ "category": shr_yield[shr_yield['Site ID'] == _row['Site ID']]['category'].iloc[0],
1033
+ "structure_index": round(float(_row['Coffee structure index']), 2)
1034
+ }
1035
+ for _, _row in site_medians.iterrows()
1036
+ }
1037
+
1038
+ # median data
1039
+ _median_data = {}
1040
+ for _, _row in shr_yield_gr_median_quant_minmax.iterrows():
1041
+ _cat = _row["category"]
1042
+ _median_data[_cat] = {
1043
+ "color": _colors[_cat],
1044
+ "css_class": get_class(_cat),
1045
+ "median_values": {_col: round(_row[f'{_col}_median'], 1) for _col in shr_num_cols_for_minmax},
1046
+ "median_values_minmax": {_col: round(_row[f'{_col}_median_minmax'], 3) for _col in shr_num_cols_for_minmax}
1047
+ }
1048
+
1049
+ _esm_code = """
1050
+ function render({ model, el }) {
1051
+
1052
+ el.innerHTML = model.get("svg");
1053
+
1054
+ const allStyles = document.querySelectorAll("style");
1055
+ const ourStyle = Array.from(allStyles).find(s =>
1056
+ s.textContent.includes("fien_notebook")
1057
+ );
1058
+
1059
+ const style = document.createElement("style");
1060
+ style.textContent = ourStyle ? ourStyle.textContent : "";
1061
+ el.insertBefore(style, el.firstChild);
1062
+
1063
+ el.style.display = "flex";
1064
+ el.style.flexDirection = "column";
1065
+ el.style.alignItems = "flex-start";
1066
+ el.style.backgroundColor = "white";
1067
+ el.style.padding = "16px";
1068
+
1069
+ setTimeout(() => {
1070
+
1071
+ const svg = el.querySelector("svg");
1072
+
1073
+ // creation of legend table
1074
+ const median_data = model.get("median_data");
1075
+ const axes = el.querySelectorAll("line.axis");
1076
+ const y_val0 = model.get("y_val0");
1077
+ const y_val1 = model.get("y_val1");
1078
+
1079
+ const cat_to_label = {
1080
+ "1_low": "Management Cluster 1 - ly",
1081
+ "1_high": "Management Cluster 1 - hy",
1082
+ "2_low": "Management Cluster 2 - ly",
1083
+ "2_high": "Management Cluster 2 - hy",
1084
+ "3_low": "Management Cluster 3 - ly",
1085
+ "3_high": "Management Cluster 3 - hy"
1086
+ };
1087
+ const cat_to_color = {
1088
+ "1_low": "#8fa8ee",
1089
+ "1_high": "#2d46dc",
1090
+ "2_low": "#c8eaaa",
1091
+ "2_high": "#91d76e",
1092
+ "3_low": "#e88a8d",
1093
+ "3_high": "#be2d32"
1094
+ };
1095
+
1096
+ const cat_to_width = {
1097
+ "1_low": 4, "1_high": 4,
1098
+ "2_low": 4, "2_high": 4,
1099
+ "3_low": 4, "3_high": 4
1100
+ };
1101
+
1102
+ const table = document.createElement("table");
1103
+ table.style.fontFamily = "sans-serif";
1104
+ table.style.fontSize = "16px";
1105
+ table.style.borderCollapse = "collapse";
1106
+ table.style.border = "2px solid #ccc";
1107
+ table.style.marginTop = "16px";
1108
+ table.style.width = "475 px";
1109
+
1110
+ const trMainTitle = document.createElement("tr");
1111
+ const tdMainTitle = document.createElement("td");
1112
+ tdMainTitle.colSpan = 4;
1113
+ tdMainTitle.textContent = "Legend - 6 categories: shrub's individual management cluster (1, 2, 3) x site's yield class (low, high)";
1114
+ tdMainTitle.style.padding = "8px 12px 4px 12px";
1115
+ tdMainTitle.style.fontWeight = "bold";
1116
+ tdMainTitle.style.fontSize = "20px";
1117
+ tdMainTitle.style.borderBottom = "1px solid #eee";
1118
+ trMainTitle.appendChild(tdMainTitle);
1119
+ table.appendChild(trMainTitle);
1120
+
1121
+ const trColHeaders = document.createElement("tr");
1122
+ [
1123
+ {text: "Shrubs (over all sites) belonging to High Yield Sites", borderLeft: false},
1124
+ {text: "", borderLeft: false},
1125
+ {text: "Shrubs (over all sites) belonging to Low Yield Sites", borderLeft: true},
1126
+ {text: "", borderLeft: false}
1127
+ ].forEach(({text, borderLeft}) => {
1128
+ const td = document.createElement("td");
1129
+ td.textContent = text;
1130
+ td.style.padding = "6px 12px 0px 12px";
1131
+ td.style.fontSize = "16px";
1132
+ td.style.fontWeight = "bold";
1133
+ if (borderLeft) td.style.borderLeft = "2px solid #ccc";
1134
+ trColHeaders.appendChild(td);
1135
+ });
1136
+ table.appendChild(trColHeaders);
1137
+
1138
+ const trColSubHeaders = document.createElement("tr");
1139
+ [
1140
+ {text: "(mean yield 2017-2019 > 1000 kg/ha)", borderLeft: false},
1141
+ {text: "", borderLeft: false},
1142
+ {text: "(mean yield 2017-2019 <= 1000 kg/ha)", borderLeft: true},
1143
+ {text: "", borderLeft: false}
1144
+ ].forEach(({text, borderLeft}) => {
1145
+ const td = document.createElement("td");
1146
+ td.textContent = text;
1147
+ td.style.padding = "0px 12px 6px 12px";
1148
+ td.style.fontSize = "13px";
1149
+ td.style.fontWeight = "bold"; // same as subtitle
1150
+ td.style.borderBottom = "1px solid #ccc";
1151
+ if (borderLeft) td.style.borderLeft = "2px solid #ccc";
1152
+ trColSubHeaders.appendChild(td);
1153
+ });
1154
+ table.appendChild(trColSubHeaders);
1155
+
1156
+ const checkboxMap = {};
1157
+
1158
+ const makeCell = (cat, borderLeft) => {
1159
+ const tdLabel = document.createElement("td");
1160
+ tdLabel.style.padding = "4px 12px";
1161
+ tdLabel.style.display = "flex";
1162
+ tdLabel.style.alignItems = "center";
1163
+ tdLabel.style.gap = "10px";
1164
+ if (borderLeft) tdLabel.style.borderLeft = "2px solid #ccc";
1165
+
1166
+ const lineSvg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
1167
+ lineSvg.setAttribute("width", "30");
1168
+ lineSvg.setAttribute("height", "10");
1169
+ const line = document.createElementNS("http://www.w3.org/2000/svg", "line");
1170
+ line.setAttribute("x1", "0"); line.setAttribute("y1", "5");
1171
+ line.setAttribute("x2", "30"); line.setAttribute("y2", "5");
1172
+ line.setAttribute("stroke", cat_to_color[cat]);
1173
+ line.setAttribute("stroke-width", cat_to_width[cat]);
1174
+ lineSvg.appendChild(line);
1175
+ tdLabel.appendChild(lineSvg);
1176
+
1177
+ const span = document.createElement("span");
1178
+ span.textContent = cat_to_label[cat] || cat;
1179
+ span.style.color = "black";
1180
+ tdLabel.appendChild(span);
1181
+
1182
+ const tdCheck = document.createElement("td");
1183
+ tdCheck.style.padding = "4px 8px";
1184
+ tdCheck.style.textAlign = "center";
1185
+
1186
+ const checkbox = document.createElement("input");
1187
+ checkbox.type = "checkbox";
1188
+ checkbox.style.cursor = "pointer";
1189
+ checkboxMap[cat] = checkbox;
1190
+ tdCheck.appendChild(checkbox);
1191
+
1192
+ return [tdLabel, tdCheck];
1193
+ };
1194
+
1195
+ const highCats = ["1_high", "2_high", "3_high"];
1196
+ const lowCats = ["1_low", "2_low", "3_low"];
1197
+
1198
+ for (let i = 0; i < 3; i++) {
1199
+ const tr = document.createElement("tr");
1200
+ const [tdLabelH, tdCheckH] = makeCell(highCats[i], false);
1201
+ const [tdLabelL, tdCheckL] = makeCell(lowCats[i], true);
1202
+ tr.appendChild(tdLabelH);
1203
+ tr.appendChild(tdCheckH);
1204
+ tr.appendChild(tdLabelL);
1205
+ tr.appendChild(tdCheckL);
1206
+ table.appendChild(tr);
1207
+ }
1208
+
1209
+ const trBottom = document.createElement("tr");
1210
+ const tdBottom = document.createElement("td");
1211
+ tdBottom.colSpan = 4;
1212
+ tdBottom.innerHTML =
1213
+ "Check boxes to show category raw median and 0.25 and 0.75 quantile values.<br>" +
1214
+ "Hover over or click on category median lines to show category 0.25 & 0.75 quantile area and light up median lines for comparison.";
1215
+ tdBottom.style.padding = "8px 12px";
1216
+ tdBottom.style.fontSize = "16px";
1217
+ tdBottom.style.color = "#666";
1218
+ tdBottom.style.borderTop = "1px solid #ccc";
1219
+ tdBottom.style.fontStyle = "bold";
1220
+ tdBottom.style.fontStyle = "italic";
1221
+ trBottom.appendChild(tdBottom);
1222
+ table.appendChild(trBottom);
1223
+
1224
+ if (!el.querySelector("div.table-wrapper")) {
1225
+ const wrapper = document.createElement("div");
1226
+ wrapper.classList.add("table-wrapper");
1227
+ wrapper.style.position = "relative";
1228
+ wrapper.style.width = "1700px";
1229
+ wrapper.style.height = "400px";
1230
+ wrapper.style.marginTop = "32px";
1231
+ table.style.position = "absolute";
1232
+ table.style.left = "0px";
1233
+ table.style.top = "0px";
1234
+ wrapper.appendChild(table);
1235
+ el.appendChild(wrapper);
1236
+ }
1237
+
1238
+ el.querySelectorAll("g[id]").forEach((g) => {
1239
+ const cat = g.getAttribute("id");
1240
+ console.log("g gevonden:", cat, "median_data aanwezig:", !!median_data[cat]);
1241
+ if (!median_data[cat]) return;
1242
+ if (g.dataset.checkboxAdded) return;
1243
+ g.dataset.checkboxAdded = "true";
1244
+
1245
+ const checkbox = checkboxMap[cat];
1246
+ if (!checkbox) return;
1247
+
1248
+ const cls = median_data[cat].css_class;
1249
+
1250
+ checkbox.addEventListener("change", () => {
1251
+ el.querySelectorAll(`text.median_label_${cat}`).forEach(label => {
1252
+ label.style.visibility = checkbox.checked ? "visible" : "hidden";
1253
+ });
1254
+ if (!checkbox.checked) {
1255
+ g.querySelectorAll("text.quantile_label").forEach(l => {
1256
+ l.style.visibility = "hidden";
1257
+ });
1258
+ }
1259
+ });
1260
+
1261
+ /* in case hover via CSS
1262
+ g.addEventListener("mouseenter", () => {
1263
+ if (!checkbox.checked) return;
1264
+ g.querySelectorAll("text.quantile_label").forEach(l => {
1265
+ l.style.visibility = "visible";
1266
+ });
1267
+ });
1268
+ g.addEventListener("mouseleave", () => {
1269
+ g.querySelectorAll("text.quantile_label").forEach(l => {
1270
+ l.style.visibility = "hidden";
1271
+ });
1272
+ });
1273
+ */
1274
+
1275
+ /* in case hover via JS - till next comment */
1276
+ let _pinned = false;
1277
+
1278
+ const medianPath = g.querySelector("path:not(.quantile_area)");
1279
+ medianPath.style.cursor = "pointer";
1280
+ const hitPath = medianPath.cloneNode();
1281
+
1282
+ hitPath.style.strokeWidth = "20";
1283
+ hitPath.style.opacity = "0.01";
1284
+ hitPath.style.fill = "none";
1285
+ hitPath.style.pointerEvents = "stroke";
1286
+ hitPath.setAttribute("stroke", "black");
1287
+ hitPath.setAttribute("stroke-width", "20");
1288
+
1289
+ g.appendChild(hitPath);
1290
+
1291
+ hitPath.addEventListener("click", () => {
1292
+ _pinned = !_pinned;
1293
+ const area = g.querySelector("path.quantile_area");
1294
+ const median = medianPath;
1295
+ if (area) area.style.opacity = _pinned ? "0.25" : "0";
1296
+ if (median) {
1297
+ median.style.filter = _pinned
1298
+ ? "drop-shadow(0px 0px 3px white)" +
1299
+ "drop-shadow(0px 0px 6px white)" +
1300
+ "drop-shadow(0px 0px 10px white)" +
1301
+ "drop-shadow(0px 0px 1px black)"
1302
+ : "";
1303
+ median.style.strokeWidth = _pinned ? "7" : "";
1304
+ }
1305
+ if (checkbox.checked) {
1306
+ g.querySelectorAll("text.quantile_label").forEach(l => {
1307
+ l.style.visibility = _pinned ? "visible" : "hidden";
1308
+ });
1309
+ }
1310
+ });
1311
+
1312
+ hitPath.addEventListener("mouseenter", () => {
1313
+ if (_pinned) return;
1314
+ const area = g.querySelector("path.quantile_area");
1315
+ const median = medianPath;
1316
+ if (area) area.style.opacity = "0.25";
1317
+ if (median) {
1318
+ median.style.filter = "drop-shadow(0px 0px 3px white)" +
1319
+ "drop-shadow(0px 0px 6px white)" +
1320
+ "drop-shadow(0px 0px 10px white)" +
1321
+ "drop-shadow(0px 0px 1px black)";
1322
+ median.style.strokeWidth = "7";
1323
+ }
1324
+ if (checkbox.checked) {
1325
+ g.querySelectorAll("text.quantile_label").forEach(l => {
1326
+ l.style.visibility = "visible";
1327
+ });
1328
+ }
1329
+ });
1330
+
1331
+ hitPath.addEventListener("mouseleave", () => {
1332
+ if (_pinned) return;
1333
+ const area = g.querySelector("path.quantile_area");
1334
+ const median = medianPath;
1335
+ if (area) area.style.opacity = "0";
1336
+ if (median) {
1337
+ median.style.filter = "";
1338
+ median.style.strokeWidth = "";
1339
+ }
1340
+ g.querySelectorAll("text.quantile_label").forEach(l => {
1341
+ l.style.visibility = "hidden";
1342
+ });
1343
+ });
1344
+ /* in case hover via JS - till here */
1345
+
1346
+ // checkboxes per site
1347
+ });
1348
+ const site_data = model.get("site_category");
1349
+ const site_ids = Object.keys(site_data);
1350
+
1351
+ // creating site checkbox table
1352
+ const siteTable = document.createElement("table");
1353
+ siteTable.style.fontFamily = "sans-serif";
1354
+ siteTable.style.fontSize = "16px";
1355
+ siteTable.style.borderCollapse = "collapse";
1356
+ siteTable.style.border = "2px solid #ccc";
1357
+ siteTable.style.marginTop = "16px";
1358
+
1359
+ // title row
1360
+ const trSiteTitle = document.createElement("tr");
1361
+ const tdSiteTitle = document.createElement("td");
1362
+ tdSiteTitle.colSpan = 6;
1363
+ tdSiteTitle.textContent = "EXTRA: Show median shrub profile per site (scaled on category median minmax scale)";
1364
+ tdSiteTitle.style.padding = "8px 12px 4px 12px";
1365
+ tdSiteTitle.style.fontWeight = "bold";
1366
+ tdSiteTitle.style.fontSize = "20px";
1367
+ tdSiteTitle.style.borderBottom = "1px solid #eee";
1368
+ trSiteTitle.appendChild(tdSiteTitle);
1369
+ siteTable.appendChild(trSiteTitle);
1370
+
1371
+ // check all / none row
1372
+ const trCheckAll = document.createElement("tr");
1373
+ const tdCheckAll = document.createElement("td");
1374
+ tdCheckAll.colSpan = 6;
1375
+ tdCheckAll.style.padding = "4px 12px";
1376
+ tdCheckAll.style.borderBottom = "1px solid #eee";
1377
+
1378
+ const checkAllBox = document.createElement("input");
1379
+ checkAllBox.type = "checkbox";
1380
+ checkAllBox.style.cursor = "pointer";
1381
+ checkAllBox.style.marginRight = "6px";
1382
+
1383
+ const checkAllLabel = document.createElement("span");
1384
+ checkAllLabel.textContent = "Select all sites / none";
1385
+ checkAllLabel.style.fontSize = "16px";
1386
+
1387
+ // save checkboxes
1388
+ const allSiteCheckboxes = [];
1389
+
1390
+ checkAllBox.addEventListener("change", () => {
1391
+ allSiteCheckboxes.forEach(({checkbox, site_id}) => {
1392
+ checkbox.checked = checkAllBox.checked;
1393
+ const sitePath = el.querySelector(`path[id="site_${site_id}"]`);
1394
+ if (sitePath) {
1395
+ sitePath.classList.toggle("visible", checkAllBox.checked);
1396
+ if (!checkAllBox.checked) {
1397
+ sitePath.classList.remove("pinned");
1398
+ const tooltip = el.querySelector(`div[data-tooltip-site="${site_id}"]`);
1399
+ if (tooltip) tooltip.style.display = "none";
1400
+ }
1401
+ }
1402
+ });
1403
+ });
1404
+
1405
+ // select all high / low yield
1406
+ const trCheckHL = document.createElement("tr");
1407
+ const tdCheckHL = document.createElement("td");
1408
+ tdCheckHL.colSpan = 6;
1409
+ tdCheckHL.style.padding = "4px 12px";
1410
+ tdCheckHL.style.borderBottom = "1px solid #eee";
1411
+ tdCheckHL.style.display = "flex";
1412
+ tdCheckHL.style.gap = "16px";
1413
+
1414
+ ["high", "low"].forEach(yield_class => {
1415
+ const wrapper = document.createElement("span");
1416
+ const box = document.createElement("input");
1417
+ box.type = "checkbox";
1418
+ box.style.cursor = "pointer";
1419
+ box.style.marginRight = "4px";
1420
+ const lbl = document.createElement("span");
1421
+ lbl.textContent = yield_class === "high" ? "All high yield" : "All low yield";
1422
+ lbl.style.fontSize = "16px";
1423
+
1424
+ box.addEventListener("change", () => {
1425
+ allSiteCheckboxes.forEach(({checkbox, site_id}) => {
1426
+ if (site_data[site_id].category.includes(yield_class)) {
1427
+ checkbox.checked = box.checked;
1428
+ const sitePath = el.querySelector(`path[id="site_${site_id}"]`);
1429
+ if (sitePath) {
1430
+ sitePath.classList.toggle("visible", box.checked);
1431
+ if (!box.checked) {
1432
+ sitePath.classList.remove("pinned");
1433
+ const tooltip = el.querySelector(`div[data-tooltip-site="${site_id}"]`);
1434
+ if (tooltip) tooltip.style.display = "none";
1435
+ }
1436
+ }
1437
+ }
1438
+ });
1439
+ });
1440
+
1441
+ wrapper.appendChild(box);
1442
+ wrapper.appendChild(lbl);
1443
+ tdCheckHL.appendChild(wrapper);
1444
+ });
1445
+
1446
+ tdCheckAll.appendChild(checkAllBox);
1447
+ tdCheckAll.appendChild(checkAllLabel);
1448
+ trCheckAll.appendChild(tdCheckAll);
1449
+ siteTable.appendChild(trCheckAll);
1450
+
1451
+ trCheckHL.appendChild(tdCheckHL);
1452
+ siteTable.appendChild(trCheckHL);
1453
+
1454
+ // checkboxes split site_ids in high en low yield
1455
+ const highYieldIds = site_ids.filter(id => site_data[id].category.includes("high"));
1456
+ const lowYieldIds = site_ids.filter(id => site_data[id].category.includes("low"));
1457
+
1458
+
1459
+
1460
+ // 2 groups checkboxes high and low yield - flex group
1461
+ const trGroups = document.createElement("tr");
1462
+ const tdGroups = document.createElement("td");
1463
+ tdGroups.colSpan = 6;
1464
+ tdGroups.style.display = "flex";
1465
+ tdGroups.style.flexDirection = "row";
1466
+ tdGroups.style.gap = "24px";
1467
+ tdGroups.style.alignItems = "flex-start";
1468
+ tdGroups.style.padding = "4px 12px";
1469
+
1470
+ const makeGroupDiv = (ids, groupLabel) => {
1471
+ const div = document.createElement("div");
1472
+ div.style.display = "flex";
1473
+ div.style.flexDirection = "column";
1474
+
1475
+ const title = document.createElement("div");
1476
+
1477
+ title.textContent = groupLabel;
1478
+ title.style.fontWeight = "bold";
1479
+ title.style.fontSize = "16px";
1480
+ title.style.color = "#444";
1481
+ title.style.borderTop = "1px solid #eee";
1482
+ title.style.padding = "6px 0px 2px 0px";
1483
+ div.appendChild(title);
1484
+
1485
+ const checkContainer = document.createElement("div");
1486
+ checkContainer.style.display = "flex";
1487
+ checkContainer.style.flexWrap = "wrap";
1488
+ checkContainer.style.width = `${4 * 110}px`;
1489
+ checkContainer.style.gap = "4px";
1490
+ div.appendChild(checkContainer);
1491
+
1492
+ ids.forEach((site_id) => {
1493
+ const row = document.createElement("div");
1494
+ row.style.display = "flex";
1495
+ row.style.alignItems = "center";
1496
+ row.style.padding = "2px 0px";
1497
+ row.style.width = "200px";
1498
+
1499
+ const checkbox = document.createElement("input");
1500
+ allSiteCheckboxes.push({checkbox, site_id});
1501
+ checkbox.type = "checkbox";
1502
+ checkbox.style.cursor = "pointer";
1503
+ checkbox.style.marginRight = "4px";
1504
+
1505
+ const structIdx = site_data[site_id]?.structure_index ?? "";
1506
+ const label = document.createElement("span");
1507
+ label.textContent = `${site_id} (${structIdx})`;
1508
+ label.style.fontSize = "16px";
1509
+
1510
+ // tooltip
1511
+ const sitePath = el.querySelector(`path[id="site_${site_id}"]`);
1512
+ if (sitePath) {
1513
+ let _pinned = false; // PIN WITH CLICK
1514
+ const tooltip = document.createElement("div");
1515
+ tooltip.setAttribute("data-tooltip-site", site_id);
1516
+ tooltip.textContent = `${site_id} (${structIdx})`;
1517
+ tooltip.style.position = "absolute";
1518
+ tooltip.style.background = "rgba(0,0,0,0.7)";
1519
+ tooltip.style.color = "white";
1520
+ tooltip.style.padding = "3px 7px";
1521
+ tooltip.style.borderRadius = "4px";
1522
+ tooltip.style.fontSize = "16px";
1523
+ tooltip.style.pointerEvents = "none";
1524
+ tooltip.style.display = "none";
1525
+ el.appendChild(tooltip);
1526
+
1527
+ checkbox.addEventListener("change", () => {
1528
+ const sitePath = el.querySelector(`path[id="site_${site_id}"]`);
1529
+ if (sitePath) {
1530
+ sitePath.classList.toggle("visible", checkbox.checked);
1531
+ if (!checkbox.checked) {
1532
+ sitePath.classList.remove("pinned");
1533
+ tooltip.style.display = "none";
1534
+ }
1535
+ }
1536
+ });
1537
+
1538
+ sitePath.addEventListener("click", () => {
1539
+ if (!sitePath.classList.contains("visible")) return;
1540
+ _pinned = !_pinned;
1541
+ sitePath.classList.toggle("pinned", _pinned);
1542
+ tooltip.style.display = _pinned ? "block" : "none";
1543
+ });
1544
+
1545
+ sitePath.addEventListener("mouseenter", (e) => {
1546
+ if (!sitePath.classList.contains("visible")) return;
1547
+ if (_pinned) return;
1548
+ tooltip.style.display = "block";
1549
+ const rect = el.getBoundingClientRect();
1550
+ tooltip.style.left = (e.clientX - rect.left + 10) + "px";
1551
+ tooltip.style.top = (e.clientY - rect.top - 20) + "px";
1552
+ });
1553
+
1554
+ sitePath.addEventListener("mousemove", (e) => {
1555
+ if (!sitePath.classList.contains("visible")) return;
1556
+ const rect = el.getBoundingClientRect();
1557
+ tooltip.style.left = (e.clientX - rect.left + 10) + "px";
1558
+ tooltip.style.top = (e.clientY - rect.top - 20) + "px";
1559
+ });
1560
+
1561
+ sitePath.addEventListener("mouseleave", () => {
1562
+ if (_pinned) return;
1563
+ tooltip.style.display = "none";
1564
+ });
1565
+ }
1566
+
1567
+ row.appendChild(checkbox);
1568
+ row.appendChild(label);
1569
+ row.style.width = "130px";
1570
+ checkContainer.appendChild(row);
1571
+ });
1572
+
1573
+ return div;
1574
+ };
1575
+
1576
+ tdGroups.appendChild(makeGroupDiv(highYieldIds, "High Yield Sites (mean yield > 1000 kg/ha )"));
1577
+ tdGroups.appendChild(makeGroupDiv(lowYieldIds, "Low Yield Sites (mean yield <= 1000 kg/ha )"));
1578
+ trGroups.appendChild(tdGroups);
1579
+ siteTable.appendChild(trGroups);
1580
+
1581
+ const trSiteBottom = document.createElement("tr");
1582
+ const tdSiteBottom = document.createElement("td");
1583
+ tdSiteBottom.colSpan = 6;
1584
+ tdSiteBottom.innerHTML =
1585
+ "Check boxes to show site shrub profiles (median values, MinMax scaled (0,1) on category median values per variable).<br>" +
1586
+ "Hover over or click on site shrub profiles to light up for comparison.";
1587
+ tdSiteBottom.style.padding = "8px 12px";
1588
+ tdSiteBottom.style.fontSize = "16px";
1589
+ tdSiteBottom.style.color = "#666";
1590
+ tdSiteBottom.style.borderTop = "1px solid #ccc";
1591
+ tdSiteBottom.style.fontStyle = "italic";
1592
+ trSiteBottom.appendChild(tdSiteBottom);
1593
+ siteTable.appendChild(trSiteBottom);
1594
+
1595
+
1596
+ if (!el.querySelector("table.site-table")) {
1597
+ siteTable.classList.add("site-table");
1598
+ siteTable.style.position = "absolute";
1599
+ siteTable.style.left = "1000px";
1600
+ siteTable.style.top = "0px";
1601
+ const wrapper = el.querySelector("div.table-wrapper");
1602
+ if (wrapper) {
1603
+ wrapper.appendChild(siteTable);
1604
+ } else {
1605
+ el.appendChild(siteTable);
1606
+ }
1607
+ }
1608
+
1609
+ }, 100);
1610
+ }
1611
+ export default { render };
1612
+ """
1613
+
1614
+ class ClickWidget(anywidget.AnyWidget):
1615
+ _esm = _esm_code
1616
+ _css = ""
1617
+ svg = traitlets.Unicode().tag(sync=True)
1618
+ median_data = traitlets.Dict().tag(sync=True)
1619
+ minmax_for_axis = traitlets.Dict().tag(sync=True)
1620
+ y_val0 = traitlets.Float().tag(sync=True)
1621
+ y_val1 = traitlets.Float().tag(sync=True)
1622
+ site_category = traitlets.Dict().tag(sync=True)
1623
+
1624
+ w = mo.ui.anywidget(ClickWidget(
1625
+ svg=svg_minmax.as_str(),
1626
+ median_data=_median_data,
1627
+ minmax_for_axis = minmax_for_axis,
1628
+ y_val0=y_val0,
1629
+ y_val1=y_val1,
1630
+ site_category=_site_data
1631
+ ))
1632
+ w
1633
+ return
1634
+
1635
+
1636
+ @app.cell
1637
+ def _(mo):
1638
+ mo.md(r"""
1639
+ <style>
1640
+ svg.fien_notebook {
1641
+ border: 1px solid;
1642
+ overflow: visible;
1643
+ }
1644
+ path.low_1:not(.quantile_area) { stroke: #b8c8f5; stroke-width: 3; fill: none; }
1645
+ path.high_1:not(.quantile_area) { stroke: #2d46dc; stroke-width: 3; fill: none; }
1646
+ path.low_2:not(.quantile_area) { stroke: #c8f0a0; stroke-width: 3; fill: none; }
1647
+ path.high_2:not(.quantile_area) { stroke: #91d76e; stroke-width: 3; fill: none; }
1648
+ path.low_3:not(.quantile_area) { stroke: #f0a0a2; stroke-width: 3; fill: none; }
1649
+ path.high_3:not(.quantile_area) { stroke: #be2d32; stroke-width: 3; fill: none; }
1650
+ line.gridline {
1651
+ stroke: black;
1652
+ stroke-width: 0.5;
1653
+ opacity: 0.2;
1654
+ }
1655
+ line.gridline_minmax_01 {
1656
+ stroke: black;
1657
+ stroke-width: 2;
1658
+ stroke-dasharray: 3, 5;
1659
+ opacity: 0.4;
1660
+ }
1661
+ line.axis {
1662
+ stroke: black;
1663
+ stroke-width: 2
1664
+ }
1665
+ text.axis_label {
1666
+ font-size: 16px;
1667
+ font-family: sans-serif;
1668
+ }
1669
+ line.arrow {
1670
+ stroke: black;
1671
+ stroke-width: 1.5;
1672
+ }
1673
+ text.axis_rv_label {
1674
+ fill: black;
1675
+ font-size: 14px;
1676
+ font-family: sans-serif;
1677
+ font-weight: bold;
1678
+ }
1679
+ text.minmax_01_labels {
1680
+ fill: #666;
1681
+ font-size: 17px;
1682
+ font-family: sans-serif;
1683
+ }
1684
+ path.quantile_area { opacity: 0; stroke: none; }
1685
+ /* hover via CSS
1686
+ path.low_1.quantile_area { fill: #b8c8f5; }
1687
+ path.high_1.quantile_area { fill: #2d46dc; }
1688
+ path.low_2.quantile_area { fill: #c8f0a0; }
1689
+ path.high_2.quantile_area { fill: #91d76e; }
1690
+ path.low_3.quantile_area { fill: #f0a0a2; }
1691
+ path.high_3.quantile_area { fill: #be2d32; }
1692
+ svg.fien_notebook g:hover path.quantile_area {
1693
+ opacity: 0.25 !important;
1694
+ }
1695
+ svg.fien_notebook g:hover path:not(.quantile_area) {
1696
+ filter:
1697
+ drop-shadow(0px 0px 3px white)
1698
+ drop-shadow(0px 0px 6px white)
1699
+ drop-shadow(0px 0px 10px white)
1700
+ drop-shadow(0px 0px 1px black);
1701
+ stroke-width: 7;
1702
+ }
1703
+ */
1704
+ path.quantile_area { pointer-events: none; }
1705
+ g.legend {
1706
+ font-family: sans-serif;
1707
+ font-size: 14px;
1708
+ }
1709
+ text.median_label {
1710
+ visibility: hidden;
1711
+ font-style: italic;
1712
+ font-family: sans-serif;
1713
+ font-size: 17px;
1714
+ font-weight: bold;
1715
+ }
1716
+ text.median_label.low_1 {
1717
+ fill: #8fa8ee;
1718
+ }
1719
+ text.median_label.high_1 {
1720
+ fill: #2d46dc;
1721
+ }
1722
+ text.median_label.low_2 {
1723
+ fill: #c8eaaa;
1724
+ }
1725
+ text.median_label.high_2 {
1726
+ fill: #91d76e;
1727
+ }
1728
+ text.median_label.low_3 {
1729
+ fill: #e88a8d;
1730
+ }
1731
+ text.median_label.high_3 {
1732
+ fill: #be2d32;
1733
+ }
1734
+ text.quantile_label {
1735
+ visibility: hidden;
1736
+ font-style: italic;
1737
+ font-family: sans-serif;
1738
+ font-size: 15px;
1739
+ }
1740
+ text.quantile_label.low_1 { fill: #8fa8ee; }
1741
+ text.quantile_label.high_1 { fill: #2d46dc; }
1742
+ text.quantile_label.low_2 { fill: #c8eaaa; }
1743
+ text.quantile_label.high_2 { fill: #91d76e; }
1744
+ text.quantile_label.low_3 { fill: #e88a8d; }
1745
+ text.quantile_label.high_3 { fill: #be2d32; }
1746
+ text.plot_title {
1747
+ font-size: 28px;
1748
+ font-weight: bold;
1749
+ font-family: sans-serif;
1750
+ }
1751
+ text.plot_subtitle {
1752
+ font-size: 16px;
1753
+ font-family: sans-serif;
1754
+ fill: #666;
1755
+ }
1756
+ text.hist_title {
1757
+ font-size: 18px;
1758
+ font-family: sans-serif;
1759
+ fill: black;
1760
+ }
1761
+ path.rug_plot {
1762
+ fill: #999999;
1763
+ opacity: 2;
1764
+ stroke: none;
1765
+ }
1766
+ line.rug_axis {
1767
+ stroke: black;
1768
+ stroke-width: 0.3;
1769
+ }
1770
+ path.site_line_high,
1771
+ path.site_line_low {
1772
+ opacity: 0;
1773
+ fill: none;
1774
+ cursor: pointer;
1775
+ }
1776
+ path.site_line_high {
1777
+ stroke: #999999;
1778
+ stroke-width: 1.75;
1779
+ }
1780
+ path.site_line_low {
1781
+ stroke: #A0522D;
1782
+ stroke-width: 1.75;
1783
+ }
1784
+ path.site_line_high.visible,
1785
+ path.site_line_low.visible {
1786
+ opacity: 0.7;
1787
+ }
1788
+ path.site_line_high.pinned,
1789
+ path.site_line_low.pinned {
1790
+ opacity: 0.8;
1791
+ stroke-width: 3.5;
1792
+ filter: drop-shadow(0px 0px 1px black) drop-shadow(0px 0px 2px black);
1793
+ }
1794
+ path.site_line_high.visible:hover,
1795
+ path.site_line_low.visible:hover {
1796
+ opacity: 0.8;
1797
+ stroke-width: 3.5;
1798
+ filter: drop-shadow(0px 0px 1px black) drop-shadow(0px 0px 2px black);
1799
+ }
1800
+ </style>
1801
+ """)
1802
+ return
1803
+
1804
+
1805
+ if __name__ == "__main__":
1806
+ app.run()