Spaces:
Sleeping
Sleeping
File size: 72,455 Bytes
6914de5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 | 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 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,
style="fill:#f5f5f5;stroke:#ccc;stroke-width:1;"
)
# 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 + _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");
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);
el.style.display = "flex";
el.style.flexDirection = "column";
el.style.alignItems = "flex-start";
el.style.backgroundColor = "white";
el.style.padding = "16px";
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.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";
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);
if (!el.querySelector("div.table-wrapper")) {
const wrapper = document.createElement("div");
wrapper.classList.add("table-wrapper");
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";
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
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})`;
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";
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");
siteTable.style.position = "absolute";
siteTable.style.left = "1000px";
siteTable.style.top = "0px";
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
}
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,
path.site_line_low {
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);
}
</style>
""")
return
if __name__ == "__main__":
app.run()
|