Spaces:
Sleeping
Sleeping
Download visual3.py from fnmrtns/marimo-app-template: direct link, hf CLI and curl.
- Browser
- Download file 78.3 kB
-
https://huggingface.co/spaces/fnmrtns/marimo-app-template/resolve/refs%2Fpr%2F8/visual3.py
- Command line
-
hf download hf://spaces/fnmrtns/marimo-app-template@refs/pr/8/visual3.py
-
curl -L -o visual3.py https://huggingface.co/spaces/fnmrtns/marimo-app-template/resolve/refs%2Fpr%2F8/visual3.py
78.3 kB
import marimo
__generated_with = "0.23.1"
app = marimo.App(width="full")
@app.cell
def _():
import marimo as mo
import pandas as pd
import numpy as np
from svg import SVG, Line, Path, G, Rect, Text
from sklearn.preprocessing import MinMaxScaler
import anywidget
import traitlets
# from scipy.stats import gaussian_kde
return G, Line, Path, Rect, SVG, Text, anywidget, mo, np, pd, traitlets
@app.cell
def _(pd):
shrubs = pd.read_excel("data/Coffee_structure_index_variables.xlsx")
c_yield = pd.read_excel("data/Coffee_yield.xlsx")
management = pd.read_excel("data/Environmental_and_management_variables.xlsx")
# merging shrub characteristics with yield of sites
shr_yield_first = pd.merge(shrubs, c_yield, on="Site ID", how="left")
shr_yield = shr_yield_first.merge(management[['Site ID', 'Coffee structure index']], on='Site ID', how='left')
return (shr_yield,)
@app.cell
def _(np, shr_yield):
# Adding for each shrub category based on fitted cluster of shrub & mean yield of its site
conditions_to_category = [
(shr_yield["Fitted cluster"] == 1) & (shr_yield["Mean_CC_Yield"] <= 1000),
(shr_yield["Fitted cluster"] == 2) & (shr_yield["Mean_CC_Yield"] <= 1000),
(shr_yield["Fitted cluster"] == 3) & (shr_yield["Mean_CC_Yield"] <= 1000),
(shr_yield["Fitted cluster"] == 1) & (shr_yield["Mean_CC_Yield"] > 1000),
(shr_yield["Fitted cluster"] == 2) & (shr_yield["Mean_CC_Yield"] > 1000),
(shr_yield["Fitted cluster"] == 3) & (shr_yield["Mean_CC_Yield"] > 1000)
]
cat_names = ['1_low', '2_low', '3_low', "1_high", "2_high", "3_high"]
shr_yield['category'] = np.select(conditions_to_category, cat_names, default='other')
return
@app.cell
def _(shr_yield):
# aggregated values for shrubs in each category (median, quantiles)
_shr_num_cols = [
'Primary orthotropic shoots',
'Secondary orthotropic shoots',
'Primary and secondary orthotropic shoots',
"Plagiotropic shoots",
"Proportion of coffee height with bearing shoots",
"Mean coffee canopy Diameter",
"Mean stem diameter at Knee Height",
]
# function to aggregate quantiles 0.25 and 0.75:
def q25(_x): return _x.quantile(0.25)
def q75(_x): return _x.quantile(0.75)
# new df _agg_values
_agg_values = shr_yield.groupby('category')[_shr_num_cols].agg(['median', q25, q75])
# names for columns in _agg_values
_agg_values.columns = ['_'.join(col) for col in _agg_values.columns]
_agg_values = _agg_values.reset_index()
# shr_yield with _agg_values
shr_yield_std_agg = shr_yield.merge(_agg_values, on='category', how='left')
# df with median and quantiles 0.5, 0.75
_columns_vis_median_quant = ['category'] + [
col for col in _agg_values.columns
if any(x in col for x in ['_median', '_q25', '_q75']) and '_std' not in col
]
shr_yield_gr_median_quant = shr_yield_std_agg[_columns_vis_median_quant].groupby('category').mean().reset_index()
return (shr_yield_gr_median_quant,)
@app.cell
def _(shr_yield_gr_median_quant):
# #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)
shr_num_cols_for_minmax = [
'Primary orthotropic shoots',
'Secondary orthotropic shoots',
'Plagiotropic shoots',
'Proportion of coffee height with bearing shoots',
'Mean coffee canopy Diameter',
'Mean stem diameter at Knee Height'
]
shr_yield_gr_median_quant_minmax = shr_yield_gr_median_quant.copy()
minmax_for_axis = {} # minmax_for_axis = to show the unscaled min and max median values as text on top/bottom of axis
for _col in shr_num_cols_for_minmax:
mincol = shr_yield_gr_median_quant[f'{_col}_median'].min() # MINMAX BASED ON MEDIAN
maxcol = shr_yield_gr_median_quant[f'{_col}_median'].max() # MINMAX BASED ON MEDIAN
minmax_for_axis[_col] = {"min": round(mincol, 1), "max": round(maxcol, 1)} # MINMAX BASED ON MEDIAN
# mincol = shr_yield_gr_median_quant[f'{_col}_q25'].min() # MINMAX BASED ON QUANTILES
# maxcol = shr_yield_gr_median_quant[f'{_col}_q75'].max() # MINMAX BASED ON QUANTILES
# minmax_for_axis[_col] = {"min": round(mincol, 1), "max": round(maxcol, 1)} # MINMAX BASED ON QUANTILES
for _suffix in ['_median', '_q25', '_q75']:
_scaled = (shr_yield_gr_median_quant[f'{_col}{_suffix}'] - mincol) / (maxcol - mincol)
shr_yield_gr_median_quant_minmax[f'{_col}{_suffix}_minmax'] = _scaled
# calculating global max and min for all colums to ensure sufficient lenght of y axis to show also quantile values outside 0,1 range
_median_q25_q75_minmax_cols = [
f'{_col}{_suffix}_minmax'
for _col in shr_num_cols_for_minmax
for _suffix in ['_median', '_q25', '_q75']
]
global_min = shr_yield_gr_median_quant_minmax[_median_q25_q75_minmax_cols].min().min()
global_max = shr_yield_gr_median_quant_minmax[_median_q25_q75_minmax_cols].max().max()
return (
global_max,
global_min,
minmax_for_axis,
shr_num_cols_for_minmax,
shr_yield_gr_median_quant_minmax,
)
@app.cell
def _(shr_yield):
shr_num_cols_sites = [
'Primary orthotropic shoots',
'Secondary orthotropic shoots',
'Plagiotropic shoots',
'Proportion of coffee height with bearing shoots',
'Mean coffee canopy Diameter',
'Mean stem diameter at Knee Height'
]
# no extra axes
# site_medians_1 = shr_yield.groupby('Site ID')[shr_num_cols_sites].median().reset_index()
# site_medians_2 = site_medians_1.merge(
# shr_yield[['Site ID', 'Coffee structure index']].drop_duplicates(),
# on='Site ID',
# how='left'
# )
# site_medians = site_medians_2.sort_values('Coffee structure index').reset_index(drop=True)
## EXTRA AXES
shr_num_cols_sites_extra = [
'Mean_CC_Yield',
'CC_Yield_2018',
'CC_Yield_2017_2019_mean',
'Coffee structure index'
]
_cols_for_merge = [
'Mean_CC_Yield',
'CC_Yield_2017',
'CC_Yield_2018',
'CC_Yield_2019',
'Coffee structure index'
]
site_medians_1 = shr_yield.groupby('Site ID')[shr_num_cols_sites].median().reset_index()
site_medians_2 = site_medians_1.merge(
shr_yield[['Site ID'] + _cols_for_merge].drop_duplicates('Site ID'),
on='Site ID',
how='left'
)
site_medians = site_medians_2.sort_values('Coffee structure index').reset_index(drop=True)
site_medians['CC_Yield_2017_2019_mean'] = (site_medians['CC_Yield_2017'] + site_medians['CC_Yield_2019']) / 2
return shr_num_cols_sites_extra, site_medians
@app.cell
def _(shr_num_cols_sites_extra, site_medians):
##SCALING FOR EXTRA AXES
# minmax schaling voor extra assen
minmax_extra = {}
# yield kolommen: geschaald op Mean_CC_Yield min/max
_yield_min = site_medians['Mean_CC_Yield'].min()
_yield_max = site_medians['Mean_CC_Yield'].max()
minmax_extra['Mean_CC_Yield'] = {"min": round(_yield_min, 1), "max": round(_yield_max, 1), "scale_min": _yield_min, "scale_max": _yield_max}
minmax_extra['CC_Yield_2018'] = {"min": round(_yield_min, 1), "max": round(_yield_max, 1), "scale_min": _yield_min, "scale_max": _yield_max}
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}
# structure index: eigen min/max
_si_min = site_medians['Coffee structure index'].min()
_si_max = site_medians['Coffee structure index'].max()
minmax_extra['Coffee structure index'] = {"min": round(_si_min, 2), "max": round(_si_max, 2), "scale_min": _si_min, "scale_max": _si_max}
# geschaalde waarden per site per extra variabele
for _col in shr_num_cols_sites_extra:
_smin = minmax_extra[_col]["scale_min"]
_smax = minmax_extra[_col]["scale_max"]
site_medians[f'{_col}_minmax'] = (site_medians[_col] - _smin) / (_smax - _smin)
return (minmax_extra,)
@app.cell
def _():
# KDE NOT USED - HISTOGRAMS INSTEAD
# calculating density curves for plotting under y axis per variable (real values, over all entities)
# # with Kernel Density Estimation (KDE)
# kde_data = {}
# for _col in kde_cols:
# _vals = shr_yield[_col].dropna().values
# _kde = gaussian_kde(_vals, bw_method=0.05)
# _x_min = _vals.min()
# _x_max = _vals.max()
# _x_range = np.linspace(_x_min, _x_max, 200)
# _density = _kde(_x_range)
# kde_data[_col] = {
# "x_min": _x_min,
# "x_max": _x_max,
# "x_range": _x_range,
# "density": _density,
# "density_max": _density.max()
# }
return
@app.cell
def _(np, shr_yield):
# calculating histograms (miniature distribution per shrub variable)
hist_cols = [
'Primary orthotropic shoots',
'Secondary orthotropic shoots',
'Plagiotropic shoots',
'Proportion of coffee height with bearing shoots',
'Mean coffee canopy Diameter',
'Mean stem diameter at Knee Height'
]
hist_data = {}
for _col in hist_cols:
_vals = shr_yield[_col].dropna().values
_counts, _bin_edges = np.histogram(_vals, bins=50)
hist_data[_col] = {
"x_min": _bin_edges[0],
"x_max": _bin_edges[-1],
"counts": _counts,
"bin_edges": _bin_edges,
"counts_max": _counts.max()
}
return hist_cols, hist_data
@app.cell
def _():
# defining width and height of svg's
svg_width = 1400 # if minmax based on quantiles: 1600 OR else 1600
svg_height = 500 # if minmax based on quantiles: 800 OR else 600
# extra space for legend
#svg_legend_width = 250
return svg_height, svg_width
@app.function
# function rescale
def rescale(_yvalue, domain_min, domain_max, range_min, range_max):
scale = (range_max - range_min) / (domain_max - domain_min)
return range_min + (_yvalue - domain_min) * scale
@app.cell
def _():
# creation of get_class function to allocate class to Paths
_class_mapping = {
"1_low": "low_1",
"1_high": "high_1",
"2_low": "low_2",
"2_high": "high_2",
"3_low": "low_3",
"3_high": "high_3"
}
def get_class(_category_value):
return _class_mapping[_category_value]
return (get_class,)
@app.cell
def _(svg_width):
# creating x values:
_left_margin = 100 # leaving a margin at the edge besides the y axis
_right_margin = 100
x_values = []
for _i in range(0, 6):
_x_i = _left_margin + (svg_width - _left_margin - _right_margin) / 5 * _i
x_values.append(_x_i)
return (x_values,)
@app.cell
def _(x_values):
## EXTRA AXES
# extra x values for new 4 axes
_x_step = (x_values[-1] - x_values[0]) / 10
_extra_offset = 100
x_values_extra = [x_values[-1] + _extra_offset + _x_step * (_i + 1) for _i in range(4)]
x_values_all = x_values + x_values_extra
## END EXTRA AXES
return x_values_all, x_values_extra
@app.cell
def _(
G,
Line,
Path,
Rect,
SVG,
Text,
get_class,
global_max,
global_min,
hist_cols,
hist_data,
minmax_extra,
minmax_for_axis,
np,
shr_num_cols_for_minmax,
shr_num_cols_sites_extra,
shr_yield,
shr_yield_gr_median_quant,
shr_yield_gr_median_quant_minmax,
site_medians,
svg_height,
svg_width,
x_values,
x_values_all,
x_values_extra,
):
## WITH MINMAX sCALING
# defining axis labels (top of axis, vertically, split after every word)
_axis_labels = [
"Nr of\nPrimary\northotropic\nshoots",
"Nr of\nSecondary\northotropic\nshoots",
"Nr of\nPlagiotropic\nshoots",
"Proportion\nof tree with\nfruit bearing\nshoots",
"Mean\nCanopy\ndiameter",
"Mean\nStem\ndiameter"
]
## EXTRA AXES
_extra_axis_labels = [
"Mean\nYield",
"Yield\n2018",
"Mean Yield\n2017 & 2019",
"Coffee\nStructure\nIndex"
]
##
# adapting _top_margin formerly created to the lenght of longest label
_top_margin = max(len(_label.split("\n")) for _label in _axis_labels) * 14 + 40
# adding padding, to give some margin at edge of SVG
_padding = 5
# adding _bottom_margin
_bottom_margin = 20
# adding title maring
_title_margin = 60
# pixel height of plot
y_val1 = _top_margin
y_val0 = svg_height - _padding
_plot_pixel_height = y_val0 - y_val1
# calculating extra space on y axis to show also quantile values outside 0,1 range (based on global_max and global_min)
_extra_top = (global_max - 1) * _plot_pixel_height
_extra_bottom = abs(min(0, global_min)) * _plot_pixel_height
# calculating actual pixel top and pixel bottom of plot
_y_top = y_val1 - _extra_top
_y_bot = y_val0 + _extra_bottom
# if _y_top = negative => shift all down
_margin = 300 # MINMAX QUANTILES = 80 else 150
_y_offset = max(0, -_y_top) + _margin + _title_margin
_y_top = _y_top + _y_offset
_y_bot = _y_bot + _y_offset
y_val0 = y_val0 + _y_offset
y_val1 = y_val1 + _y_offset
# creating _label_elements = y axis labels
_label_elements = []
for _x, _label in zip(x_values, _axis_labels):
_words = _label.split("\n")
for _idx, _word in enumerate(_words):
_label_elements.append(
Text(
x=_x + _idx * 12 + 50,
y=_y_top - 40,
text=_word,
font_size=10,
text_anchor="start",
transform=f"rotate(-90, {_x + _idx * 12 + 15}, {_y_top - 10})",
class_="axis_label"
)
)
# selecting columns for creation of _y_values (_minmax median values) (prim+sec orthotrop not incl)
_cols_median = [
col for col in shr_yield_gr_median_quant_minmax.columns
if '_median' in col and "_minmax" in col and "Primary and secondary orthotropic shoots" not in col
]
# selecting columns for creation of quantile lines 0.25 and 0.75
_cols_q25 = [
col for col in shr_yield_gr_median_quant_minmax.columns
if '_q25' in col and "_minmax" in col and "Primary and secondary orthotropic shoots" not in col
]
_cols_q75 = [
col for col in shr_yield_gr_median_quant_minmax.columns
if '_q75' in col and "_minmax" in col and "Primary and secondary orthotropic shoots" not in col
]
# function to create Paths and quantile lines and group them in group per category
def _create_path(_row):
_class = get_class(_row["category"])
_fill_colors = {
"low_1": "#b8c8f5", "high_1": "#2d46dc",
"low_2": "#c8f0a0", "high_2": "#91d76e",
"low_3": "#f0a0a2", "high_3": "#be2d32"
}
# median
_y_median = [rescale(v, 0, 1, y_val0, y_val1) for v in _row[_cols_median].tolist()]
_d_median = f"M {x_values[0]},{_y_median[0]} " + \
" ".join(f"L {_x},{_y}" for _x, _y in zip(x_values[1:], _y_median[1:]))
# q25 line and q75 line and filled area in between
_y_q25 = [rescale(v, 0, 1, y_val0, y_val1) for v in _row[_cols_q25].tolist()]
_y_q75 = [rescale(v, 0, 1, y_val0, y_val1) for v in _row[_cols_q75].tolist()]
_d_area = (
f"M {x_values[0]},{_y_q75[0]} " +
" ".join(f"L {_x},{_y}" for _x, _y in zip(x_values[1:], _y_q75[1:])) +
f" L {x_values[-1]},{_y_q25[-1]} " +
" ".join(f"L {_x},{_y}" for _x, _y in zip(reversed(x_values[:-1]), reversed(_y_q25[:-1]))) +
" Z"
)
# QUANTILE LABELS WITH HOVER
_qlabel_elements = []
for _x, _col, _yq25, _yq75 in zip(x_values, shr_num_cols_for_minmax, _y_q25, _y_q75):
_val_q25_display = round(_row[f'{_col}_q25'], 1)
_val_q75_display = round(_row[f'{_col}_q75'], 1)
_qlabel_elements.append(
Text(
x=_x + 5,
y=_yq25 + 10,
text=str(_val_q25_display),
font_size=10,
class_=f"quantile_label {_class}"
)
)
_qlabel_elements.append(
Text(
x=_x + 5,
y=_yq75 - 3,
text=str(_val_q75_display),
font_size=10,
class_=f"quantile_label {_class}"
)
)
return G(
id=str(_row["category"]),
elements=[
Path(d=_d_area, class_=f"{_class} quantile_area", style=f"fill:{_fill_colors[_class]};opacity:0;stroke:none;"),
Path(d=_d_median, class_=_class)
] + _qlabel_elements
)
# creating path elements ( median, q25, q75)
_path_elements_minmax = []
for _, _row in shr_yield_gr_median_quant_minmax.iterrows():
_path_elements_minmax.append(_create_path(_row))
# creating shrub elements to show individual shrubs
_shrub_cat_classes = {
"1_low": "low_1", "1_high": "high_1",
"2_low": "low_2", "2_high": "high_2",
"3_low": "low_3", "3_high": "high_3"
}
_cat_colors = {
"low_1": "#b8c8f5", "high_1": "#2d46dc",
"low_2": "#c8f0a0", "high_2": "#91d76e",
"low_3": "#f0a0a2", "high_3": "#be2d32"
}
_shrub_elements = []
for _, _row in shr_yield.iterrows():
_cat = _row['category']
if _cat == 'other':
continue
_shrub_color = _cat_colors.get(_cat, "#999999")
_y_values_shrub = []
for _col in shr_num_cols_for_minmax:
_mincol = shr_yield_gr_median_quant[f'{_col}_median'].min()
_maxcol = shr_yield_gr_median_quant[f'{_col}_median'].max()
_scaled = (_row[_col] - _mincol) / (_maxcol - _mincol)
_y_values_shrub.append(rescale(_scaled, 0, 1, y_val0, y_val1))
_d_shrub = f"M {x_values[0]},{_y_values_shrub[0]} " + \
" ".join(f"L {_x},{_y}" for _x, _y in zip(x_values[1:], _y_values_shrub[1:]))
_shrub_elements.append(
Path(
d=_d_shrub,
class_=f"shrub_line {_shrub_cat_classes[_cat]}"
)
)
# creating site median paths (grey background lines)
_site_elements = []
for _, _row in site_medians.iterrows():
_site_id = str(_row['Site ID'])
_cat = shr_yield[shr_yield['Site ID'] == _row['Site ID']]['category'].iloc[0]
_y_values = []
for _col in shr_num_cols_for_minmax:
_mincol = shr_yield_gr_median_quant[f'{_col}_median'].min()
_maxcol = shr_yield_gr_median_quant[f'{_col}_median'].max()
_scaled = (_row[_col] - _mincol) / (_maxcol - _mincol)
_y_values.append(rescale(_scaled, 0, 1, y_val0, y_val1))
## EXTRA AXES
_y_values_extra = []
for _col in shr_num_cols_sites_extra:
_scaled = _row[f'{_col}_minmax']
_y_values_extra.append(rescale(_scaled, 0, 1, y_val0, y_val1))
_y_values_all = _y_values + _y_values_extra
_d_site = f"M {x_values_all[0]},{_y_values_all[0]} " + \
" ".join(f"L {_x},{_y}" for _x, _y in zip(x_values_all[1:], _y_values_all[1:]))
## NO EXTRA AXES
# _d_site = f"M {x_values[0]},{_y_values[0]} " + \
# " ".join(f"L {_x},{_y}" for _x, _y in zip(x_values[1:], _y_values[1:]))
_site_class = "site_line_high" if "high" in _cat else "site_line_low"
_site_elements.append(
Path(
d=_d_site,
id=f"site_{_site_id}",
class_=_site_class,
)
)
# creating grid lines
_grid_start = np.floor(global_min / 0.25) * 0.25
_grid_end = np.ceil(global_max / 0.25) * 0.25
_gridlines_values = np.arange(_grid_start, _grid_end + 0.25, 0.25).tolist()
_grid_elements_minmax = []
for _i in _gridlines_values:
_y = rescale(_i, 0, 1, y_val0, y_val1)
if _y >= _y_top:
_grid_elements_minmax.append(
Line(
x1=x_values[0],
y1=_y,
x2=x_values[-1],
y2=_y,
class_="gridline"
)
)
# creating black dashed gridlines for minmax 0 and 1 values
for _x in x_values:
_y1 = rescale(1, 0, 1, y_val0, y_val1)
_grid_elements_minmax.append(
Line(
x1=x_values[0] - 30,
y1=_y1,
x2=x_values[-1],
y2=_y1,
class_="gridline_minmax_01"
)
)
_y0 = rescale(0, 0, 1, y_val0, y_val1)
_grid_elements_minmax.append(
Line(
x1=x_values[0] - 30,
y1=_y0,
x2=x_values[-1],
y2=_y0,
class_="gridline_minmax_01"
)
)
break # to only execute once, so not for all gridlines but only 0 1 minmax values
## EXTRA AXES
# creating black dashed gridlines 0 and 1 for extra axes section
_y1_extra = rescale(1, 0, 1, y_val0, y_val1)
_y0_extra = rescale(0, 0, 1, y_val0, y_val1)
_grid_elements_minmax.append(
Line(
x1=x_values_extra[0],
y1=_y1_extra,
x2=x_values_extra[-1],
y2=_y1_extra,
class_="gridline_minmax_01"
)
)
_grid_elements_minmax.append(
Line(
x1=x_values_extra[0],
y1=_y0_extra,
x2=x_values_extra[-1],
y2=_y0_extra,
class_="gridline_minmax_01"
)
)
###
# creating axis
_axis_elements = []
_extra_lenght_y_axis_ontop = 30
for _i in x_values:
_axis_elements.append(
Line(
x1=_i,
y1=_y_top - _extra_lenght_y_axis_ontop,
x2=_i,
y2=_y_bot + _extra_lenght_y_axis_ontop,
class_="axis"
)
)
# creating axis heads (arrows on top)
_arrow_elements = []
for _i in x_values:
_arrow_elements.append(
Line(x1=_i - 5, y1=_y_top - 18, x2=_i, y2=_y_top - _extra_lenght_y_axis_ontop, class_="arrow")
)
_arrow_elements.append(
Line(x1=_i + 5, y1=_y_top - 18, x2=_i, y2=_y_top - _extra_lenght_y_axis_ontop, class_="arrow")
)
## EXTRA AXES - creating extra axes
for _i in x_values_extra:
_axis_elements.append(
Line(
x1=_i,
y1=_y_top - _extra_lenght_y_axis_ontop,
x2=_i,
y2=_y_bot + _extra_lenght_y_axis_ontop,
class_="axis"
)
)
_arrow_elements.append(
Line(x1=_i - 5, y1=_y_top - 18, x2=_i, y2=_y_top - _extra_lenght_y_axis_ontop, class_="arrow")
)
_arrow_elements.append(
Line(x1=_i + 5, y1=_y_top - 18, x2=_i, y2=_y_top - _extra_lenght_y_axis_ontop, class_="arrow")
)
# creating fixed min and max median values on y axis (real median values displayed, not minmax transformed)
_rv_label_elements = []
for _x, _col in zip(x_values, shr_num_cols_for_minmax):
# definig min and max median values
_max_val = shr_yield_gr_median_quant_minmax[f'{_col}_median_minmax'].max() # MINMAX BASED ON MEDIAN
_min_val = shr_yield_gr_median_quant_minmax[f'{_col}_median_minmax'].min() # MINMAX BASED ON MEDIAN
# calculating position on y axis
_y_max = rescale(_max_val, 0, 1, y_val0, y_val1) # MINMAX BASED ON MEDIAN
_y_min = rescale(_min_val, 0, 1, y_val0, y_val1) # MINMAX BASED ON MEDIAN
# _y_max = rescale(1, 0, 1, y_val0, y_val1) # MINMAX BASED ON QUANTILES
# _y_min = rescale(0, 0, 1, y_val0, y_val1) # MINMAX BASED ON QUANTILES
_rv_label_elements.append(
Text(
x=_x + 5,
y=_y_max - 10,
text=str(minmax_for_axis[_col]["max"]),
font_size=9,
class_="axis_rv_label"
)
)
_rv_label_elements.append(
Text(
x=_x + 5,
y=_y_min - 10,
text=str(minmax_for_axis[_col]["min"]),
font_size=9,
class_="axis_rv_label"
)
)
_rv_label_elements.append(
Text(
x=_x + 5,
y=rescale(0.5, 0, 1, y_val0, y_val1) - 10,
text=str(round(minmax_for_axis[_col]["min"] + 0.5 * \
(minmax_for_axis[_col]["max"] - minmax_for_axis[_col]["min"]), 1)),
font_size=9,
class_="axis_rv_label"
)
)
# # creating fixed middle y axis values - NOT KEPT
# _mid_val_display = round((minmax_for_axis[_col]["min"] + minmax_for_axis[_col]["max"]) / 2, 1)
# _y_mid = rescale(0.5, 0, 1, y_val0, y_val1)
# _minmax_label_elements.append(
# Text(
# x=_x + 5,
# y=_y_mid + 4,
# text=str(_mid_val_display),
# font_size=9,
# class_="axis_minmax_label"
# )
# )
# extra gridlines: 0.25, 0.5, 0.75 and value above [0,1]
# extra _minmax_label_elements as gridline (on under gridline only showing for 4th y axis as other values would be
# negative or non-informative)
_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]]
for _i in _extra_gridlines:
_real_val = round(
minmax_for_axis[_col]["min"] + _i * (minmax_for_axis[_col]["max"] - minmax_for_axis[_col]["min"]),
1
)
_y = rescale(_i, 0, 1, y_val0, y_val1)
if _real_val > 2:
_rv_label_elements.append(
Text(
x=_x + 5,
y=_y + 10,
text=str(_real_val),
font_size=9,
class_="axis_rv_label")
)
# minmax 0 en 1 labels, accompanying minmax 0 and 1 dash line
for _x in x_values:
_y1 = rescale(1, 0, 1, y_val0, y_val1)
_y0 = rescale(0, 0, 1, y_val0, y_val1)
_rv_label_elements.append(
Text(
x=_x - 15,
y=_y1 + 10,
text="MinMax 1",
font_size=8,
text_anchor="end",
class_="minmax_01_labels"
)
)
_rv_label_elements.append(
Text(
x=_x - 15,
y=_y0 + 10,
text="MinMax 0",
font_size=8,
text_anchor="end",
class_="minmax_01_labels"
)
)
break # to only execute once, for the first y axis, not for the others
##EXTRA AXES - creating axes labels and rv labels
for _x, _col, _label in zip(x_values_extra, shr_num_cols_sites_extra, _extra_axis_labels):
# extra axes labels
_words = _label.split("\n")
for _idx, _word in enumerate(_words):
_label_elements.append(
Text(
x=_x + _idx * 12 + 30,
y=_y_top - 60,
text=_word,
font_size=10,
text_anchor="start",
transform=f"rotate(-90, {_x + _idx * 12 + 15}, {_y_top - 30})",
class_="axis_label"
)
)
# extra axes min max rv labels
_real_min = minmax_extra[_col]["min"]
_real_max = minmax_extra[_col]["max"]
_real_mid = round(_real_min + 0.5 * (_real_max - _real_min), 1)
_rv_label_elements.append(
Text(x=_x + 5, y=rescale(1, 0, 1, y_val0, y_val1) - 10,
text=str(_real_max), font_size=9, class_="axis_rv_label")
)
_rv_label_elements.append(
Text(x=_x + 5, y=rescale(0, 0, 1, y_val0, y_val1) - 10,
text=str(_real_min), font_size=9, class_="axis_rv_label")
)
_rv_label_elements.append(
Text(x=_x + 5, y=rescale(0.5, 0, 1, y_val0, y_val1) - 10,
text=str(_real_mid), font_size=9, class_="axis_rv_label")
)
##
# tick elements for gridline labels on y axis
_tick_elements = []
for _i in [0, 0.5, 1,
1.5, # MINMAX MEDIAN else comment
]:
_y = rescale(_i, 0, 1, y_val0, y_val1)
if _y >= _y_top:
for _x in x_values:
_tick_elements.append(
Line(
x1=_x - 4,
y1=_y,
x2=_x + 4,
y2=_y,
class_="axis"
)
)
# extra tick element for 4th axis under extra gridline
_tick_elements.append(
Line(
x1= x_values[3] - 4,
y1= rescale(-0.5, 0, 1, y_val0, y_val1),
x2= x_values[3] + 4,
y2= rescale(-0.5, 0, 1, y_val0, y_val1),
class_="axis"
)
)
## EXTRA AXES - ticks for extra axes
for _i in [0, 0.5, 1, 1.5]:
_y = rescale(_i, 0, 1, y_val0, y_val1)
if _y >= _y_top:
for _x in x_values_extra:
_tick_elements.append(
Line(
x1=_x - 4,
y1=_y,
x2=_x + 4,
y2=_y,
class_="axis"
)
)
# creating median labels, shown when checkbox is ticked via anywidget
_median_label_elements = []
for _, _row in shr_yield_gr_median_quant_minmax.iterrows():
_class = get_class(_row["category"])
for _x, _col in zip(x_values, shr_num_cols_for_minmax):
_val_minmax = _row[f'{_col}_median_minmax']
_val_display = round(_row[f'{_col}_median'], 1)
_y = rescale(_val_minmax, 0, 1, y_val0, y_val1)
_median_label_elements.append(
Text(
x=_x - 35,
y=_y - 15,
text=str(_val_display),
font_size=11,
class_=f"median_label {_class} median_label_{_row['category']}",
)
)
# creation of histogram elements (rug old name from former rug_plot)
_rug_strip_top = _y_bot + 120
_rug_strip_height = 40
_offset_rug = 30
_rug_elements = []
for _x, _col in zip(x_values, hist_cols):
_d = hist_data[_col]
_half_width = 60
# baseline
_rug_elements.append(
Line(
x1=_x - _half_width + _offset_rug,
y1=_rug_strip_top + _rug_strip_height,
x2=_x + _half_width + _offset_rug,
y2=_rug_strip_top + _rug_strip_height,
class_="rug_axis"
)
)
# mini x as
_rug_elements.append(
Line(
x1=_x - _half_width + _offset_rug,
y1=_rug_strip_top,
x2=_x - _half_width + _offset_rug,
y2=_rug_strip_top + _rug_strip_height,
class_="rug_axis"
)
)
# histogram bins
for _i in range(len(_d["counts"])):
_x_left = _x + (_d["bin_edges"][_i] - _d["x_min"]) / (_d["x_max"] - _d["x_min"]) * 2 * _half_width - _half_width + _offset_rug
_x_right = _x + (_d["bin_edges"][_i+1] - _d["x_min"]) / (_d["x_max"] - _d["x_min"]) * 2 * _half_width - _half_width + _offset_rug
_bar_height = (_d["counts"][_i] / _d["counts_max"]) * _rug_strip_height
_y_top_bar = _rug_strip_top + _rug_strip_height - _bar_height
if _d["counts"][_i] > 0:
_rug_elements.append(
Path(
d=f"M {_x_left},{_rug_strip_top + _rug_strip_height} " +
f"L {_x_left},{_y_top_bar} " +
f"L {_x_right},{_y_top_bar} " +
f"L {_x_right},{_rug_strip_top + _rug_strip_height} Z",
class_="hist_plot"
)
)
# histogram title
_rug_elements.append(
Text(
x=svg_width / 5,
y=_rug_strip_top - 40,
text="Distribution of raw observed values over all categories per variable",
font_size=9,
text_anchor="middle",
class_="hist_title"
)
)
# creating legend (used in JS)
legend_items = [
("low_1", "#8fa8ee", 1, "Cluster 1 - low yield"), # light blue
("high_1", "#2d46dc", 4, "Cluster 1 - high yield"), # dark blue
("low_2", "#c8eaaa", 1, "Cluster 2 - low yield"), # light green
("high_2", "#91d76e", 4, "Cluster 2 - high yield"), # dark green
("low_3", "#e88a8d", 1, "Cluster 3 - low yield"), # light red
("high_3", "#be2d32", 4, "Cluster 3 - high yield"), # dark red
]
## LEGEND NOT USED HERE - IMPLEMENTED VIA ANYWIDGET SO CAN BE POSITIONED OUTSIDE SVG FRAME
# _legend_elements = []
# for _idx, (_id, _color, _width, _label) in enumerate(legend_items):
# _y_pos = 20 + _idx * 30
# _legend_elements.append(
# G(
# id=_id,
# elements=[
# Line(
# x1=0, y1=0,
# x2=30, y2=0,
# stroke=_color,
# stroke_width=_width
# ),
# Text(
# x=40, y=5,
# text=_label,
# font_size=11
# )
# ],
# transform=f"translate(0, {_y_pos})"
# )
# )
# _legend_group = G(
# elements=_legend_elements,
# transform=f"translate({svg_width + 40}, {_top_margin})" # position legend: right side of visual, height of plot
# )
# creating title above plot
_title = Text(
x=svg_width / 2,
y=_title_margin/2,
text="Shrub profiles by shrub's individual management cluster x site's yield class",
font_size= 20,
text_anchor="middle",
class_="plot_title"
)
# creating subtitles above plot
_subtitle = Text(
x=svg_width / 2,
y=_title_margin/2 + 22,
text="Shrub profile for 6 categories: shrub's individual management cluster (1, 2 or 3) x site's yield class (low, high)",
font_size=13,
text_anchor="middle",
class_="plot_subtitle"
)
_subtitle2 = Text(
x=svg_width / 2,
y=_title_margin/2 + 44,
text="Median values per category, with 0.25 and 0.75 quantiles, MinMax scaled (0,1) on median category values per variable",
font_size=13,
text_anchor="middle",
class_="plot_subtitle"
)
## EXTRA AXES - FILL BEHIND EXTRA AXES
_extra_bg = Rect(
x=x_values_extra[0] - 50,
y=_y_top - 160,
width=x_values_extra[-1] - x_values_extra[0] + 100,
height=_y_bot - _y_top + 200,
class_="extra_axes_bg"
)
# showing SVG
svg_minmax = SVG(
#width=svg_width, ## NO EXTRA AXES
#+ svg_legend_width,
width=x_values_extra[-1] + 150, ## EXTRA AXES
height = _rug_strip_top + _rug_strip_height + _bottom_margin,
class_="fien_notebook",
elements=[_title, _subtitle, _subtitle2] + [_extra_bg] + _grid_elements_minmax + _axis_elements + _tick_elements + _arrow_elements + _label_elements + \
_rv_label_elements + _median_label_elements + _shrub_elements + _site_elements + _path_elements_minmax + _rug_elements # +[_legend_group]
)
return legend_items, svg_minmax, y_val0, y_val1
@app.cell
def _(
anywidget,
get_class,
legend_items,
minmax_for_axis,
mo,
shr_num_cols_for_minmax,
shr_yield,
shr_yield_gr_median_quant_minmax,
site_medians,
svg_minmax,
traitlets,
y_val0,
y_val1,
):
# median values per categorie (unscaled + minmax for y position)
_colors = {
"1_low": legend_items[0][1],
"1_high": legend_items[1][1],
"2_low": legend_items[2][1],
"2_high": legend_items[3][1],
"3_low": legend_items[4][1],
"3_high": legend_items[5][1],
}
# site categories
_site_data = {
str(_row['Site ID']): {
"category": shr_yield[shr_yield['Site ID'] == _row['Site ID']]['category'].iloc[0],
"structure_index": round(float(_row['Coffee structure index']), 2)
}
for _, _row in site_medians.iterrows()
}
# median data
_median_data = {}
for _, _row in shr_yield_gr_median_quant_minmax.iterrows():
_cat = _row["category"]
_median_data[_cat] = {
"color": _colors[_cat],
"css_class": get_class(_cat),
"median_values": {_col: round(_row[f'{_col}_median'], 1) for _col in shr_num_cols_for_minmax},
"median_values_minmax": {_col: round(_row[f'{_col}_median_minmax'], 3) for _col in shr_num_cols_for_minmax}
}
_esm_code = """
function render({ model, el }) {
el.innerHTML = model.get("svg");
el.classList.add("widget-container");
const allStyles = document.querySelectorAll("style");
const ourStyle = Array.from(allStyles).find(s =>
s.textContent.includes("fien_notebook")
);
const style = document.createElement("style");
style.textContent = ourStyle ? ourStyle.textContent : "";
el.insertBefore(style, el.firstChild);
//IMPLEMENTED VIA CSS
/*el.style.display = "flex";
el.style.flexDirection = "column";
el.style.alignItems = "flex-start";
el.style.backgroundColor = "white";
el.style.padding = "16px";*/
//END VIA CSS
setTimeout(() => {
const svg = el.querySelector("svg");
// creation of legend table
const median_data = model.get("median_data");
const axes = el.querySelectorAll("line.axis");
const y_val0 = model.get("y_val0");
const y_val1 = model.get("y_val1");
const cat_to_label = {
"1_low": "Management Cluster 1 - ly",
"1_high": "Management Cluster 1 - hy",
"2_low": "Management Cluster 2 - ly",
"2_high": "Management Cluster 2 - hy",
"3_low": "Management Cluster 3 - ly",
"3_high": "Management Cluster 3 - hy"
};
const cat_to_color = {
"1_low": "#8fa8ee",
"1_high": "#2d46dc",
"2_low": "#c8eaaa",
"2_high": "#91d76e",
"3_low": "#e88a8d",
"3_high": "#be2d32"
};
const cat_to_width = {
"1_low": 4, "1_high": 4,
"2_low": 4, "2_high": 4,
"3_low": 4, "3_high": 4
};
const table = document.createElement("table");
table.classList.add("legend-table");
//VIA CSS IMPLEMENTED
/* table.style.fontFamily = "sans-serif";
table.style.fontSize = "16px";
table.style.borderCollapse = "collapse";
table.style.border = "2px solid #ccc";
table.style.marginTop = "16px";
table.style.width = "475 px"; */
// END VIA CSS
const trMainTitle = document.createElement("tr");
const tdMainTitle = document.createElement("td");
tdMainTitle.colSpan = 4;
tdMainTitle.textContent = "Legend - 6 categories: shrub's individual management cluster (1, 2, 3) x site's yield class (low, high)";
tdMainTitle.style.padding = "8px 12px 4px 12px";
tdMainTitle.style.fontWeight = "bold";
tdMainTitle.style.fontSize = "20px";
tdMainTitle.style.borderBottom = "1px solid #eee";
trMainTitle.appendChild(tdMainTitle);
table.appendChild(trMainTitle);
const trColHeaders = document.createElement("tr");
[
{text: "Shrubs (over all sites) belonging to High Yield Sites", borderLeft: false},
{text: "", borderLeft: false},
{text: "Shrubs (over all sites) belonging to Low Yield Sites", borderLeft: true},
{text: "", borderLeft: false}
].forEach(({text, borderLeft}) => {
const td = document.createElement("td");
td.textContent = text;
td.style.padding = "6px 12px 0px 12px";
td.style.fontSize = "16px";
td.style.fontWeight = "bold";
if (borderLeft) td.style.borderLeft = "2px solid #ccc";
trColHeaders.appendChild(td);
});
table.appendChild(trColHeaders);
const trColSubHeaders = document.createElement("tr");
[
{text: "(mean yield 2017-2019 > 1000 kg/ha)", borderLeft: false},
{text: "", borderLeft: false},
{text: "(mean yield 2017-2019 <= 1000 kg/ha)", borderLeft: true},
{text: "", borderLeft: false}
].forEach(({text, borderLeft}) => {
const td = document.createElement("td");
td.textContent = text;
td.style.padding = "0px 12px 6px 12px";
td.style.fontSize = "13px";
td.style.fontWeight = "bold"; // same as subtitle
td.style.borderBottom = "1px solid #ccc";
if (borderLeft) td.style.borderLeft = "2px solid #ccc";
trColSubHeaders.appendChild(td);
});
table.appendChild(trColSubHeaders);
const checkboxMap = {};
const makeCell = (cat, borderLeft) => {
const tdLabel = document.createElement("td");
tdLabel.style.padding = "4px 12px";
tdLabel.style.display = "flex";
tdLabel.style.alignItems = "center";
tdLabel.style.gap = "10px";
if (borderLeft) tdLabel.style.borderLeft = "2px solid #ccc";
const lineSvg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
lineSvg.setAttribute("width", "30");
lineSvg.setAttribute("height", "10");
const line = document.createElementNS("http://www.w3.org/2000/svg", "line");
line.setAttribute("x1", "0"); line.setAttribute("y1", "5");
line.setAttribute("x2", "30"); line.setAttribute("y2", "5");
line.setAttribute("stroke", cat_to_color[cat]);
line.setAttribute("stroke-width", cat_to_width[cat]);
lineSvg.appendChild(line);
tdLabel.appendChild(lineSvg);
const span = document.createElement("span");
span.textContent = cat_to_label[cat] || cat;
span.style.color = "black";
tdLabel.appendChild(span);
const tdCheck = document.createElement("td");
tdCheck.style.padding = "4px 8px";
tdCheck.style.textAlign = "center";
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.style.cursor = "pointer";
checkboxMap[cat] = checkbox;
tdCheck.appendChild(checkbox);
return [tdLabel, tdCheck];
};
const highCats = ["1_high", "2_high", "3_high"];
const lowCats = ["1_low", "2_low", "3_low"];
for (let i = 0; i < 3; i++) {
const tr = document.createElement("tr");
const [tdLabelH, tdCheckH] = makeCell(highCats[i], false);
const [tdLabelL, tdCheckL] = makeCell(lowCats[i], true);
tr.appendChild(tdLabelH);
tr.appendChild(tdCheckH);
tr.appendChild(tdLabelL);
tr.appendChild(tdCheckL);
table.appendChild(tr);
}
const trBottom = document.createElement("tr");
const tdBottom = document.createElement("td");
tdBottom.colSpan = 4;
tdBottom.innerHTML =
"Check boxes to show category raw median and 0.25 and 0.75 quantile values.<br>" +
"Hover over or click on category median lines to show category 0.25 & 0.75 quantile area and light up median lines for comparison.";
tdBottom.style.padding = "8px 12px";
tdBottom.style.fontSize = "16px";
tdBottom.style.color = "#666";
tdBottom.style.borderTop = "1px solid #ccc";
tdBottom.style.fontStyle = "bold";
tdBottom.style.fontStyle = "italic";
trBottom.appendChild(tdBottom);
table.appendChild(trBottom);
//extra checkbox to show shrub values
const trShrub = document.createElement("tr");
const tdShrub = document.createElement("td");
tdShrub.colSpan = 4;
tdShrub.style.padding = "8px 12px";
tdShrub.style.borderTop = "1px solid #ccc";
tdShrub.style.display = "flex";
tdShrub.style.alignItems = "center";
tdShrub.style.gap = "10px";
const shrubCheckbox = document.createElement("input");
shrubCheckbox.type = "checkbox";
shrubCheckbox.id = "shrub-all-checkbox";
shrubCheckbox.style.cursor = "pointer";
shrubCheckbox.checked = false;
const shrubLabel = document.createElement("label");
shrubLabel.htmlFor = "shrub-all-checkbox";
shrubLabel.textContent = "Show all individual shrub values";
shrubLabel.style.fontFamily = "sans-serif";
shrubLabel.style.fontSize = "16px";
shrubLabel.style.cursor = "pointer";
shrubLabel.style.fontStyle = "italic";
shrubLabel.style.color = "#444";
tdShrub.appendChild(shrubCheckbox);
tdShrub.appendChild(shrubLabel);
trShrub.appendChild(tdShrub);
table.appendChild(trShrub);
shrubCheckbox.addEventListener("change", () => {
el.querySelectorAll("path.shrub_line").forEach(p => {
p.style.opacity = shrubCheckbox.checked ? "0.08" : "0";
});
});
//end extra checkbox to show shrub values
if (!el.querySelector("div.table-wrapper")) {
const wrapper = document.createElement("div");
wrapper.classList.add("table-wrapper");
// VIA CSS IMPLMENTED
/* wrapper.style.position = "relative";
wrapper.style.width = "1700px";
wrapper.style.height = "400px";
wrapper.style.marginTop = "32px";
table.style.position = "absolute";
table.style.left = "0px";
table.style.top = "0px"; */
// END VIA CSS
wrapper.appendChild(table);
el.appendChild(wrapper);
}
el.querySelectorAll("g[id]").forEach((g) => {
const cat = g.getAttribute("id");
console.log("g gevonden:", cat, "median_data aanwezig:", !!median_data[cat]);
if (!median_data[cat]) return;
if (g.dataset.checkboxAdded) return;
g.dataset.checkboxAdded = "true";
const checkbox = checkboxMap[cat];
if (!checkbox) return;
const cls = median_data[cat].css_class;
checkbox.addEventListener("change", () => {
el.querySelectorAll(`text.median_label_${cat}`).forEach(label => {
label.style.visibility = checkbox.checked ? "visible" : "hidden";
});
if (!checkbox.checked) {
g.querySelectorAll("text.quantile_label").forEach(l => {
l.style.visibility = "hidden";
});
}
});
/* in case hover via CSS
g.addEventListener("mouseenter", () => {
if (!checkbox.checked) return;
g.querySelectorAll("text.quantile_label").forEach(l => {
l.style.visibility = "visible";
});
});
g.addEventListener("mouseleave", () => {
g.querySelectorAll("text.quantile_label").forEach(l => {
l.style.visibility = "hidden";
});
});
*/
/* in case hover via JS - till next comment */
let _pinned = false;
const medianPath = g.querySelector("path:not(.quantile_area)");
medianPath.style.cursor = "pointer";
const hitPath = medianPath.cloneNode();
hitPath.style.strokeWidth = "20";
hitPath.style.opacity = "0.01";
hitPath.style.fill = "none";
hitPath.style.pointerEvents = "stroke";
hitPath.setAttribute("stroke", "black");
hitPath.setAttribute("stroke-width", "20");
g.appendChild(hitPath);
hitPath.addEventListener("click", () => {
_pinned = !_pinned;
const area = g.querySelector("path.quantile_area");
const median = medianPath;
if (area) area.style.opacity = _pinned ? "0.25" : "0";
if (median) {
median.style.filter = _pinned
? "drop-shadow(0px 0px 3px white)" +
"drop-shadow(0px 0px 6px white)" +
"drop-shadow(0px 0px 10px white)" +
"drop-shadow(0px 0px 1px black)"
: "";
median.style.strokeWidth = _pinned ? "7" : "";
}
if (checkbox.checked) {
g.querySelectorAll("text.quantile_label").forEach(l => {
l.style.visibility = _pinned ? "visible" : "hidden";
});
}
});
hitPath.addEventListener("mouseenter", () => {
if (_pinned) return;
const area = g.querySelector("path.quantile_area");
const median = medianPath;
if (area) area.style.opacity = "0.25";
if (median) {
median.style.filter = "drop-shadow(0px 0px 3px white)" +
"drop-shadow(0px 0px 6px white)" +
"drop-shadow(0px 0px 10px white)" +
"drop-shadow(0px 0px 1px black)";
median.style.strokeWidth = "7";
}
if (checkbox.checked) {
g.querySelectorAll("text.quantile_label").forEach(l => {
l.style.visibility = "visible";
});
}
});
hitPath.addEventListener("mouseleave", () => {
if (_pinned) return;
const area = g.querySelector("path.quantile_area");
const median = medianPath;
if (area) area.style.opacity = "0";
if (median) {
median.style.filter = "";
median.style.strokeWidth = "";
}
g.querySelectorAll("text.quantile_label").forEach(l => {
l.style.visibility = "hidden";
});
});
/* in case hover via JS - till here */
// checkboxes per site
});
const site_data = model.get("site_category");
const site_ids = Object.keys(site_data);
// creating site checkbox table
const siteTable = document.createElement("table");
siteTable.style.fontFamily = "sans-serif";
siteTable.style.fontSize = "16px";
siteTable.style.borderCollapse = "collapse";
siteTable.style.border = "2px solid #ccc";
siteTable.style.marginTop = "16px";
// title row
const trSiteTitle = document.createElement("tr");
const tdSiteTitle = document.createElement("td");
tdSiteTitle.colSpan = 6;
tdSiteTitle.textContent = "EXTRA: Show median shrub profile per site (scaled on category median minmax scale)";
tdSiteTitle.style.padding = "8px 12px 4px 12px";
tdSiteTitle.style.fontWeight = "bold";
tdSiteTitle.style.fontSize = "20px";
tdSiteTitle.style.borderBottom = "1px solid #eee";
trSiteTitle.appendChild(tdSiteTitle);
siteTable.appendChild(trSiteTitle);
// check all / none row
const trCheckAll = document.createElement("tr");
const tdCheckAll = document.createElement("td");
tdCheckAll.colSpan = 6;
tdCheckAll.style.padding = "4px 12px";
tdCheckAll.style.borderBottom = "1px solid #eee";
const checkAllBox = document.createElement("input");
checkAllBox.type = "checkbox";
checkAllBox.style.cursor = "pointer";
checkAllBox.style.marginRight = "6px";
const checkAllLabel = document.createElement("span");
checkAllLabel.textContent = "Select all sites / none";
checkAllLabel.style.fontSize = "16px";
// save checkboxes
const allSiteCheckboxes = [];
checkAllBox.addEventListener("change", () => {
allSiteCheckboxes.forEach(({checkbox, site_id}) => {
checkbox.checked = checkAllBox.checked;
const sitePath = el.querySelector(`path[id="site_${site_id}"]`);
if (sitePath) {
sitePath.classList.toggle("visible", checkAllBox.checked);
if (!checkAllBox.checked) {
sitePath.classList.remove("pinned");
const tooltip = el.querySelector(`div[data-tooltip-site="${site_id}"]`);
if (tooltip) tooltip.style.display = "none";
}
}
});
});
// select all high / low yield
const trCheckHL = document.createElement("tr");
const tdCheckHL = document.createElement("td");
tdCheckHL.colSpan = 6;
tdCheckHL.style.padding = "4px 12px";
tdCheckHL.style.borderBottom = "1px solid #eee";
tdCheckHL.style.display = "flex";
tdCheckHL.style.gap = "16px";
["high", "low"].forEach(yield_class => {
const wrapper = document.createElement("span");
const box = document.createElement("input");
box.type = "checkbox";
box.style.cursor = "pointer";
box.style.marginRight = "4px";
const lbl = document.createElement("span");
lbl.textContent = yield_class === "high" ? "All high yield" : "All low yield";
lbl.style.fontSize = "16px";
box.addEventListener("change", () => {
allSiteCheckboxes.forEach(({checkbox, site_id}) => {
if (site_data[site_id].category.includes(yield_class)) {
checkbox.checked = box.checked;
const sitePath = el.querySelector(`path[id="site_${site_id}"]`);
if (sitePath) {
sitePath.classList.toggle("visible", box.checked);
if (!box.checked) {
sitePath.classList.remove("pinned");
const tooltip = el.querySelector(`div[data-tooltip-site="${site_id}"]`);
if (tooltip) tooltip.style.display = "none";
}
}
}
});
});
wrapper.appendChild(box);
wrapper.appendChild(lbl);
tdCheckHL.appendChild(wrapper);
});
tdCheckAll.appendChild(checkAllBox);
tdCheckAll.appendChild(checkAllLabel);
trCheckAll.appendChild(tdCheckAll);
siteTable.appendChild(trCheckAll);
trCheckHL.appendChild(tdCheckHL);
siteTable.appendChild(trCheckHL);
// checkboxes split site_ids in high en low yield
const highYieldIds = site_ids.filter(id => site_data[id].category.includes("high"));
const lowYieldIds = site_ids.filter(id => site_data[id].category.includes("low"));
// 2 groups checkboxes high and low yield - flex group
const trGroups = document.createElement("tr");
const tdGroups = document.createElement("td");
tdGroups.colSpan = 6;
tdGroups.style.display = "flex";
tdGroups.style.flexDirection = "row";
tdGroups.style.gap = "24px";
tdGroups.style.alignItems = "flex-start";
tdGroups.style.padding = "4px 12px";
const makeGroupDiv = (ids, groupLabel) => {
const div = document.createElement("div");
div.style.display = "flex";
div.style.flexDirection = "column";
const title = document.createElement("div");
title.textContent = groupLabel;
title.style.fontWeight = "bold";
title.style.fontSize = "16px";
title.style.color = "#444";
title.style.borderTop = "1px solid #eee";
title.style.padding = "6px 0px 2px 0px";
div.appendChild(title);
const checkContainer = document.createElement("div");
checkContainer.style.display = "flex";
checkContainer.style.flexWrap = "wrap";
checkContainer.style.width = `${4 * 110}px`;
checkContainer.style.gap = "4px";
div.appendChild(checkContainer);
ids.forEach((site_id) => {
const row = document.createElement("div");
row.style.display = "flex";
row.style.alignItems = "center";
row.style.padding = "2px 0px";
row.style.width = "200px";
const checkbox = document.createElement("input");
allSiteCheckboxes.push({checkbox, site_id});
checkbox.type = "checkbox";
checkbox.style.cursor = "pointer";
checkbox.style.marginRight = "4px";
const structIdx = site_data[site_id]?.structure_index ?? "";
const label = document.createElement("span");
label.textContent = `${site_id} (${structIdx})`;
label.style.fontSize = "16px";
// tooltip site lines
const sitePath = el.querySelector(`path[id="site_${site_id}"]`);
if (sitePath) {
let _pinned = false; // PIN WITH CLICK
const tooltip = document.createElement("div");
tooltip.setAttribute("data-tooltip-site", site_id);
tooltip.textContent = `${site_id} (${structIdx})`;
//VIA CSS IM£LEMENTED
/* tooltip.style.position = "absolute";
tooltip.style.background = "rgba(0,0,0,0.7)";
tooltip.style.color = "white";
tooltip.style.padding = "3px 7px";
tooltip.style.borderRadius = "4px";
tooltip.style.fontSize = "16px";
tooltip.style.pointerEvents = "none";
tooltip.style.display = "none"; */
// END VIA CSS
el.appendChild(tooltip);
checkbox.addEventListener("change", () => {
const sitePath = el.querySelector(`path[id="site_${site_id}"]`);
if (sitePath) {
sitePath.classList.toggle("visible", checkbox.checked);
if (!checkbox.checked) {
sitePath.classList.remove("pinned");
tooltip.style.display = "none";
}
}
});
sitePath.addEventListener("click", () => {
if (!sitePath.classList.contains("visible")) return;
_pinned = !_pinned;
sitePath.classList.toggle("pinned", _pinned);
tooltip.style.display = _pinned ? "block" : "none";
});
sitePath.addEventListener("mouseenter", (e) => {
if (!sitePath.classList.contains("visible")) return;
if (_pinned) return;
tooltip.style.display = "block";
const rect = el.getBoundingClientRect();
tooltip.style.left = (e.clientX - rect.left + 10) + "px";
tooltip.style.top = (e.clientY - rect.top - 20) + "px";
});
sitePath.addEventListener("mousemove", (e) => {
if (!sitePath.classList.contains("visible")) return;
const rect = el.getBoundingClientRect();
tooltip.style.left = (e.clientX - rect.left + 10) + "px";
tooltip.style.top = (e.clientY - rect.top - 20) + "px";
});
sitePath.addEventListener("mouseleave", () => {
if (_pinned) return;
tooltip.style.display = "none";
});
}
row.appendChild(checkbox);
row.appendChild(label);
row.style.width = "130px";
checkContainer.appendChild(row);
});
return div;
};
tdGroups.appendChild(makeGroupDiv(highYieldIds, "High Yield Sites (mean yield > 1000 kg/ha )"));
tdGroups.appendChild(makeGroupDiv(lowYieldIds, "Low Yield Sites (mean yield <= 1000 kg/ha )"));
trGroups.appendChild(tdGroups);
siteTable.appendChild(trGroups);
const trSiteBottom = document.createElement("tr");
const tdSiteBottom = document.createElement("td");
tdSiteBottom.colSpan = 6;
tdSiteBottom.innerHTML =
"Check boxes to show site shrub profiles (median values, MinMax scaled (0,1) on category median values per variable).<br>" +
"Hover over or click on site shrub profiles to light up for comparison.";
tdSiteBottom.style.padding = "8px 12px";
tdSiteBottom.style.fontSize = "16px";
tdSiteBottom.style.color = "#666";
tdSiteBottom.style.borderTop = "1px solid #ccc";
tdSiteBottom.style.fontStyle = "italic";
trSiteBottom.appendChild(tdSiteBottom);
siteTable.appendChild(trSiteBottom);
if (!el.querySelector("table.site-table")) {
siteTable.classList.add("site-table");
//VIA CSS IMPLEMENTED
/* siteTable.style.position = "absolute";
siteTable.style.left = "1000px";
siteTable.style.top = "0px"; */
// END CSS
const wrapper = el.querySelector("div.table-wrapper");
if (wrapper) {
wrapper.appendChild(siteTable);
} else {
el.appendChild(siteTable);
}
}
}, 100);
}
export default { render };
"""
class ClickWidget(anywidget.AnyWidget):
_esm = _esm_code
_css = ""
svg = traitlets.Unicode().tag(sync=True)
median_data = traitlets.Dict().tag(sync=True)
minmax_for_axis = traitlets.Dict().tag(sync=True)
y_val0 = traitlets.Float().tag(sync=True)
y_val1 = traitlets.Float().tag(sync=True)
site_category = traitlets.Dict().tag(sync=True)
w = mo.ui.anywidget(ClickWidget(
svg=svg_minmax.as_str(),
median_data=_median_data,
minmax_for_axis = minmax_for_axis,
y_val0=y_val0,
y_val1=y_val1,
site_category=_site_data
))
w
return
@app.cell
def _(mo):
mo.md(r"""
<style>
svg.fien_notebook {
border: 1px solid;
overflow: visible;
}
path.low_1:not(.quantile_area) { stroke: #b8c8f5; stroke-width: 3; fill: none; }
path.high_1:not(.quantile_area) { stroke: #2d46dc; stroke-width: 3; fill: none; }
path.low_2:not(.quantile_area) { stroke: #c8f0a0; stroke-width: 3; fill: none; }
path.high_2:not(.quantile_area) { stroke: #91d76e; stroke-width: 3; fill: none; }
path.low_3:not(.quantile_area) { stroke: #f0a0a2; stroke-width: 3; fill: none; }
path.high_3:not(.quantile_area) { stroke: #be2d32; stroke-width: 3; fill: none; }
line.gridline {
stroke: black;
stroke-width: 0.5;
opacity: 0.2;
}
line.gridline_minmax_01 {
stroke: black;
stroke-width: 2;
stroke-dasharray: 3, 5;
opacity: 0.4;
}
line.axis {
stroke: black;
stroke-width: 2
}
rect.extra_axes_bg {
fill:#f5f5f5;
stroke:#ccc;
stroke-width:1;
}
text.axis_label {
font-size: 16px;
font-family: sans-serif;
}
line.arrow {
stroke: black;
stroke-width: 1.5;
}
text.axis_rv_label {
fill: black;
font-size: 14px;
font-family: sans-serif;
font-weight: bold;
}
text.minmax_01_labels {
fill: #666;
font-size: 17px;
font-family: sans-serif;
}
path.quantile_area { opacity: 0; stroke: none; }
/* hover via CSS
path.low_1.quantile_area { fill: #b8c8f5; }
path.high_1.quantile_area { fill: #2d46dc; }
path.low_2.quantile_area { fill: #c8f0a0; }
path.high_2.quantile_area { fill: #91d76e; }
path.low_3.quantile_area { fill: #f0a0a2; }
path.high_3.quantile_area { fill: #be2d32; }
svg.fien_notebook g:hover path.quantile_area {
opacity: 0.25 !important;
}
svg.fien_notebook g:hover path:not(.quantile_area) {
filter:
drop-shadow(0px 0px 3px white)
drop-shadow(0px 0px 6px white)
drop-shadow(0px 0px 10px white)
drop-shadow(0px 0px 1px black);
stroke-width: 7;
}
*/
path.quantile_area { pointer-events: none; }
g.legend {
font-family: sans-serif;
font-size: 14px;
}
text.median_label {
visibility: hidden;
font-style: italic;
font-family: sans-serif;
font-size: 17px;
font-weight: bold;
}
text.median_label.low_1 {
fill: #8fa8ee;
}
text.median_label.high_1 {
fill: #2d46dc;
}
text.median_label.low_2 {
fill: #c8eaaa;
}
text.median_label.high_2 {
fill: #91d76e;
}
text.median_label.low_3 {
fill: #e88a8d;
}
text.median_label.high_3 {
fill: #be2d32;
}
text.quantile_label {
visibility: hidden;
font-style: italic;
font-family: sans-serif;
font-size: 15px;
}
text.quantile_label.low_1 { fill: #8fa8ee; }
text.quantile_label.high_1 { fill: #2d46dc; }
text.quantile_label.low_2 { fill: #c8eaaa; }
text.quantile_label.high_2 { fill: #91d76e; }
text.quantile_label.low_3 { fill: #e88a8d; }
text.quantile_label.high_3 { fill: #be2d32; }
text.plot_title {
font-size: 28px;
font-weight: bold;
font-family: sans-serif;
}
text.plot_subtitle {
font-size: 16px;
font-family: sans-serif;
fill: #666;
}
text.hist_title {
font-size: 18px;
font-family: sans-serif;
fill: black;
}
path.rug_plot {
fill: #999999;
opacity: 2;
stroke: none;
}
line.rug_axis {
stroke: black;
stroke-width: 0.3;
}
path.site_line_high:not(.shrub_line),
path.site_line_low:not(.shrub_line) {
opacity: 0;
fill: none;
cursor: pointer;
}
path.site_line_high {
stroke: #999999;
stroke-width: 1.75;
}
path.site_line_low {
stroke: #A0522D;
stroke-width: 1.75;
}
path.site_line_high.visible,
path.site_line_low.visible {
opacity: 0.7;
}
path.site_line_high.pinned,
path.site_line_low.pinned {
opacity: 0.8;
stroke-width: 3.5;
filter: drop-shadow(0px 0px 1px black) drop-shadow(0px 0px 2px black);
}
path.site_line_high.visible:hover,
path.site_line_low.visible:hover {
opacity: 0.8;
stroke-width: 3.5;
filter: drop-shadow(0px 0px 1px black) drop-shadow(0px 0px 2px black);
}
path.shrub_line {
opacity: 0;
fill: none;
pointer-events: none;
stroke-width: 1.5;
stroke: #999999;
}
path.shrub_line.low_1 { stroke: #b8c8f5; }
path.shrub_line.high_1 { stroke: #2d46dc; }
path.shrub_line.low_2 { stroke: #c8f0a0; }
path.shrub_line.high_2 { stroke: #91d76e; }
path.shrub_line.low_3 { stroke: #f0a0a2; }
path.shrub_line.high_3 { stroke: #be2d32; }
table.legend-table {
font-family: sans-serif;
font-size: 16px;
border-collapse: collapse;
border: 2px solid #ccc;
margin-top: 16px;
}
table.site-table {
font-family: sans-serif;
font-size: 16px;
border-collapse: collapse;
border: 2px solid #ccc;
margin-top: 16px;
}
div[data-tooltip-site] {
position: absolute;
background: rgba(0,0,0,0.7);
color: white;
padding: 3px 7px;
border-radius: 4px;
font-size: 16px;
pointer-events: none;
display: none;
font-family: sans-serif;
}
div[data-tooltip-site].visible {
display: block;
}
div.table-wrapper {
position: relative;
width: 1700px;
height: 400px;
margin-top: 32px;
}
div.table-wrapper table.legend-table {
position: absolute;
left: 0px;
top: 0px;
}
div.table-wrapper table.site-table {
position: absolute;
left: 1000px;
top: 0px;
}
.widget-container {
display: flex;
flex-direction: column;
align-items: flex-start;
background-color: white;
padding: 16px;
}
</style>
""")
return
if __name__ == "__main__":
app.run()
import marimo
__generated_with = "0.23.1"
app = marimo.App(width="full")
def _():
import marimo as mo
import pandas as pd
import numpy as np
from svg import SVG, Line, Path, G, Rect, Text
from sklearn.preprocessing import MinMaxScaler
import anywidget
import traitlets
# from scipy.stats import gaussian_kde
return G, Line, Path, Rect, SVG, Text, anywidget, mo, np, pd, traitlets
def _(pd):
shrubs = pd.read_excel("data/Coffee_structure_index_variables.xlsx")
c_yield = pd.read_excel("data/Coffee_yield.xlsx")
management = pd.read_excel("data/Environmental_and_management_variables.xlsx")
# merging shrub characteristics with yield of sites
shr_yield_first = pd.merge(shrubs, c_yield, on="Site ID", how="left")
shr_yield = shr_yield_first.merge(management[['Site ID', 'Coffee structure index']], on='Site ID', how='left')
return (shr_yield,)
def _(np, shr_yield):
# Adding for each shrub category based on fitted cluster of shrub & mean yield of its site
conditions_to_category = [
(shr_yield["Fitted cluster"] == 1) & (shr_yield["Mean_CC_Yield"] <= 1000),
(shr_yield["Fitted cluster"] == 2) & (shr_yield["Mean_CC_Yield"] <= 1000),
(shr_yield["Fitted cluster"] == 3) & (shr_yield["Mean_CC_Yield"] <= 1000),
(shr_yield["Fitted cluster"] == 1) & (shr_yield["Mean_CC_Yield"] > 1000),
(shr_yield["Fitted cluster"] == 2) & (shr_yield["Mean_CC_Yield"] > 1000),
(shr_yield["Fitted cluster"] == 3) & (shr_yield["Mean_CC_Yield"] > 1000)
]
cat_names = ['1_low', '2_low', '3_low', "1_high", "2_high", "3_high"]
shr_yield['category'] = np.select(conditions_to_category, cat_names, default='other')
return
def _(shr_yield):
# aggregated values for shrubs in each category (median, quantiles)
_shr_num_cols = [
'Primary orthotropic shoots',
'Secondary orthotropic shoots',
'Primary and secondary orthotropic shoots',
"Plagiotropic shoots",
"Proportion of coffee height with bearing shoots",
"Mean coffee canopy Diameter",
"Mean stem diameter at Knee Height",
]
# function to aggregate quantiles 0.25 and 0.75:
def q25(_x): return _x.quantile(0.25)
def q75(_x): return _x.quantile(0.75)
# new df _agg_values
_agg_values = shr_yield.groupby('category')[_shr_num_cols].agg(['median', q25, q75])
# names for columns in _agg_values
_agg_values.columns = ['_'.join(col) for col in _agg_values.columns]
_agg_values = _agg_values.reset_index()
# shr_yield with _agg_values
shr_yield_std_agg = shr_yield.merge(_agg_values, on='category', how='left')
# df with median and quantiles 0.5, 0.75
_columns_vis_median_quant = ['category'] + [
col for col in _agg_values.columns
if any(x in col for x in ['_median', '_q25', '_q75']) and '_std' not in col
]
shr_yield_gr_median_quant = shr_yield_std_agg[_columns_vis_median_quant].groupby('category').mean().reset_index()
return (shr_yield_gr_median_quant,)
def _(shr_yield_gr_median_quant):
# #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)
shr_num_cols_for_minmax = [
'Primary orthotropic shoots',
'Secondary orthotropic shoots',
'Plagiotropic shoots',
'Proportion of coffee height with bearing shoots',
'Mean coffee canopy Diameter',
'Mean stem diameter at Knee Height'
]
shr_yield_gr_median_quant_minmax = shr_yield_gr_median_quant.copy()
minmax_for_axis = {} # minmax_for_axis = to show the unscaled min and max median values as text on top/bottom of axis