Files changed (1) hide show
  1. visual1.py +1134 -1134
visual1.py CHANGED
@@ -1,1134 +1,1134 @@
1
- import marimo
2
-
3
- __generated_with = "0.11.26"
4
- app = marimo.App(width="medium")
5
-
6
-
7
- @app.cell
8
- def _():
9
- import marimo as mo
10
- import pandas as pd
11
- import math
12
- from svg import SVG, Circle, Text, G, Line, Ellipse, Rect, Title
13
- import numpy as np
14
- return Circle, Ellipse, G, Line, Rect, SVG, Text, Title, math, mo, np, pd
15
-
16
-
17
- @app.cell
18
- def _(pd):
19
- # ===== IMPORT DATASETS =====
20
- coffeeyield = pd.read_excel("data/Coffee_yield.xlsx")
21
- coffeestructureindex_management = pd.read_excel("data/Environmental_and_management_variables.xlsx")
22
- plant_species_richness = pd.read_excel("data/Plant_species_richness.xlsx")
23
- return coffeestructureindex_management, coffeeyield, plant_species_richness
24
-
25
-
26
- @app.cell
27
- def _(pd):
28
- # ===== PREPARE WOODY DATA =====
29
-
30
- #Load the excelfile
31
- woody_species_abundance = pd.read_excel("data/Woody_species_abundance.xlsx")
32
- woody_species_abundance
33
-
34
- #Creating dataframe of total abundance of woody species, per Site ID
35
- woody_totals = woody_species_abundance.iloc[:, 1:].sum().reset_index()
36
-
37
- #Rename the columns to meaningful names
38
- woody_totals.columns = ["Site ID", "Woody_total"]
39
-
40
- #Normalise the abundance values to 0-100 scale for comparability
41
- #Divide each value by max (0-1 scale) and multiply by 100 (0-100 scale)
42
- woody_totals["Woody_abundance"] = (woody_totals["Woody_total"] / woody_totals["Woody_total"].max()) * 100
43
-
44
- #Keep only the Site ID and normalised abundance columns
45
- w_abundance = woody_totals[["Site ID", "Woody_abundance"]]
46
- #w_abundance
47
- return w_abundance, woody_species_abundance, woody_totals
48
-
49
-
50
- @app.cell
51
- def _(pd):
52
- # ===== PREPARE BRYOPHYTE DATA =====
53
-
54
- #Load the txtfile
55
- bryophyte_species_abundance = pd.read_csv("data/Bryophyte_frequency.txt", sep="\t")
56
-
57
- #Creating dataframe of total abundance of bryo species, per Site ID
58
- bryo_totals = bryophyte_species_abundance.iloc[:, 1:].sum().reset_index()
59
-
60
- #Rename the columns to meaningful names
61
- bryo_totals.columns = ["Site ID", "Bryo_total"]
62
-
63
- #Normalise the abundance values to 0-100 scale for comparability
64
- #Divide each value by max (0-1 scale) and multiply by 100 (0-100 scale)
65
- bryo_totals["Bryo_abundance"] = (bryo_totals["Bryo_total"] / bryo_totals["Bryo_total"].max()) * 100
66
-
67
- #Keep only the Site ID and normalised abundance columns
68
- b_abundance = bryo_totals[["Site ID", "Bryo_abundance"]]
69
- #b_abundance
70
- return b_abundance, bryo_totals, bryophyte_species_abundance
71
-
72
-
73
- @app.cell(hide_code=True)
74
- def _():
75
- # # ===== VERIFY BRYOPHYTE DATA =====
76
-
77
- # # See the raw totals BEFORE normalization
78
- # print("Raw bryophyte totals (before normalization):")
79
- # print(bryo_totals[["Site ID", "Bryo_total"]])
80
-
81
- # # See which site has the max
82
- # print(f"\nMax bryo total: {bryo_totals['Bryo_total'].max()}")
83
-
84
- # # Check a specific site (e.g., Ge1)
85
- # ge1_row = bryo_totals[bryo_totals["Site ID"] == "Ge1"]
86
- # if not ge1_row.empty:
87
- # ge1_raw = ge1_row["Bryo_total"].values[0]
88
- # print(f"Ge1 raw total: {ge1_raw}")
89
-
90
- # # Verify the normalization calculation manually
91
- # ge1_normalized_manual = (ge1_raw / bryo_totals["Bryo_total"].max()) * 100
92
- # ge1_normalized_actual = ge1_row["Bryo_abundance"].values[0]
93
-
94
- # print(f"Ge1 normalized (manual calc): {ge1_normalized_manual:.2f}")
95
- # print(f"Ge1 normalized (from data): {ge1_normalized_actual:.2f}")
96
- # print(f"Match: {abs(ge1_normalized_manual - ge1_normalized_actual) < 0.01}")
97
- # else:
98
- # print("Ge1 not found in data")
99
-
100
- # # Show distribution
101
- # print(f"\nBryo abundance range: {bryo_totals['Bryo_abundance'].min():.2f} to {bryo_totals['Bryo_abundance'].max():.2f}")
102
-
103
- # # Display final result
104
- # print("\nFinal bryophyte abundance (0-100 scale):")
105
- # print(b_abundance.head(10))
106
- return
107
-
108
-
109
- @app.cell
110
- def _(pd):
111
- # ===== PREPARE HERB DATA =====
112
-
113
- #Load the txtfile
114
- herb_species_abundance = pd.read_csv("data/Herbaceous_vegetation_Abundance.txt", sep="\t")
115
-
116
- #Set Site ID as index and then sum species columns for total abundance
117
- herb_totals = herb_species_abundance.set_index(herb_species_abundance.columns[0]).iloc[:, :].sum(axis=1).reset_index()
118
-
119
- #Rename the columns to meaningful names
120
- herb_totals.columns = ["Site ID", "Herb_total"]
121
-
122
- #Normalise the abundance values to 0-100 scale for comparability
123
- #Divide each value by max (0-1 scale) and multiply by 100 (0-100 scale)
124
- herb_totals["Herb_abundance"] = (herb_totals["Herb_total"] / herb_totals["Herb_total"].max()) * 100
125
- herb_totals
126
-
127
- #Keep only the Site ID and normalised abundance columns
128
- h_abundance = herb_totals[["Site ID", "Herb_abundance"]]
129
- #h_abundance
130
- return h_abundance, herb_species_abundance, herb_totals
131
-
132
-
133
- @app.cell
134
- def _(
135
- b_abundance,
136
- coffeestructureindex_management,
137
- coffeeyield,
138
- h_abundance,
139
- plant_species_richness,
140
- w_abundance,
141
- ):
142
- merged = coffeeyield \
143
- .merge(coffeestructureindex_management, on="Site ID") \
144
- .merge(plant_species_richness, on="Site ID") \
145
- .merge(w_abundance, on="Site ID")\
146
- .merge(b_abundance, on="Site ID")\
147
- .merge(h_abundance, on="Site ID")
148
- merged
149
- return (merged,)
150
-
151
-
152
- @app.cell
153
- def _(filtered_flowers, filtered_for_plot, pd):
154
- # ===== PREPARE CLUSTER DATA FOR HISTOGRAMS =====
155
- cluster_data = pd.read_excel("data/Coffee_structure_index_variables.xlsx")
156
-
157
- # Simple: group by Site ID and cluster, count rows
158
- cluster_counts = cluster_data.groupby(['Site ID', 'Fitted cluster']).size().unstack(fill_value=0)
159
-
160
- # Make sure we have columns 1, 2, 3 (add if missing)
161
- for col in [1, 2, 3]:
162
- if col not in cluster_counts.columns:
163
- cluster_counts[col] = 0
164
-
165
- # Keep only sites we're showing
166
- cluster_counts = cluster_counts[cluster_counts.index.isin(filtered_flowers['Site ID'])]
167
-
168
- # Sort to match graph order
169
- site_order = filtered_for_plot[filtered_for_plot['Site ID'].isin(cluster_counts.index)].set_index('Site ID')
170
- cluster_counts = cluster_counts.loc[site_order.index]
171
-
172
- # FIX: Rename integer columns to strings
173
- cluster_counts.columns = cluster_counts.columns.astype(str)
174
-
175
- #cluster_counts
176
- return cluster_counts, cluster_data, col, site_order
177
-
178
-
179
- @app.cell
180
- def _(filter_selector, merged, pd):
181
- # ===== PREPARE DATA FOR VISUALISATION. =====
182
-
183
- # ===== CREATING TWO VARIABLES FOR SELECTOR: one for plotting whole graph, one for filtering flowers only =====
184
-
185
- #Determine which sites to display (all variables for axis/background)
186
- filtered_for_plot = merged.copy()
187
- filtered_for_plot = filtered_for_plot.sort_values("Coffee structure index").reset_index(drop=True)
188
- filtered_for_plot["ordinal_pos"] = range(1, len(filtered_for_plot) + 1)
189
-
190
- # Define min/max yield for ALL sites (needed for axes)
191
- filtered_for_plot["min_yield"] = filtered_for_plot[["CC_Yield_2017", "CC_Yield_2018", "CC_Yield_2019"]].min(axis=1, skipna=True)
192
- filtered_for_plot["max_yield"] = filtered_for_plot[["CC_Yield_2017", "CC_Yield_2018", "CC_Yield_2019"]].max(axis=1, skipna=True)
193
-
194
- #Determine which flowers are shown (changes based on filter)
195
- if filter_selector.value == "All sites":
196
- filtered_flowers = filtered_for_plot.copy()
197
- show_labels = False
198
- else: # "Top 10 + Bottom 10 yield"
199
- t10 = merged.nlargest(10, "Mean_CC_Yield")
200
- b10 = merged.nsmallest(10, "Mean_CC_Yield")
201
- filtered_flowers = pd.concat([t10, b10]).sort_values("Coffee structure index").reset_index(drop=True)
202
- show_labels = True
203
-
204
- # Add ordinal_pos, min_yield, max_yield from filtered_for_plot + add if to avoid duplicates (every time code runs)
205
- if "ordinal_pos" not in filtered_flowers.columns:
206
- filtered_flowers = filtered_flowers.merge(
207
- filtered_for_plot[["Site ID", "ordinal_pos", "min_yield", "max_yield"]],
208
- on="Site ID",
209
- how="left"
210
- )
211
-
212
- # ===== PREPERATION OF RICHNESS VARIABLE: CALCULATE MIN/MAX RICHNESS FOR NORMALIZATION =====
213
- herb_richness_min = filtered_flowers["Veg_Spps"].min()
214
- herb_richness_max = filtered_flowers["Veg_Spps"].max()
215
- bryo_richness_min = filtered_flowers["Bryo_Spps"].min()
216
- bryo_richness_max = filtered_flowers["Bryo_Spps"].max()
217
- woody_richness_min = filtered_flowers["Woody_Spps"].min()
218
- woody_richness_max = filtered_flowers["Woody_Spps"].max()
219
-
220
- # Function to normalize richness and convert to opacity in petals
221
- def get_opacity_from_richness(value, min_val, max_val):
222
- if max_val == min_val: # Handle case where all values are the same
223
- normalized = 0.5
224
- else:
225
- normalized = (value - min_val) / (max_val - min_val)
226
- return 0.2 + (normalized * 0.8) # Maps to 0.2-1.0 opacity range
227
-
228
-
229
- # ===== EXTRACT VARIABLES for plotting ======
230
- structureindex = filtered_for_plot["Coffee structure index"]
231
- mean_coffee_yield = filtered_for_plot["Mean_CC_Yield"]
232
- site_id = filtered_for_plot["Site ID"]
233
- herb_abundance = filtered_for_plot["Herb_abundance"]
234
- bryo_abundance = filtered_for_plot["Bryo_abundance"]
235
- woody_abundance = filtered_for_plot["Woody_abundance"]
236
- ordinal_pos = filtered_for_plot["ordinal_pos"]
237
-
238
- #Extract variables for flowers (filtered)
239
- flower_sites = filtered_flowers["Site ID"].tolist()
240
-
241
- print(f"All sites to display: {len(filtered_for_plot)}")
242
- print(f"Flowers to show: {len(filtered_flowers)}")
243
- return (
244
- b10,
245
- bryo_abundance,
246
- bryo_richness_max,
247
- bryo_richness_min,
248
- filtered_flowers,
249
- filtered_for_plot,
250
- flower_sites,
251
- get_opacity_from_richness,
252
- herb_abundance,
253
- herb_richness_max,
254
- herb_richness_min,
255
- mean_coffee_yield,
256
- ordinal_pos,
257
- show_labels,
258
- site_id,
259
- structureindex,
260
- t10,
261
- woody_abundance,
262
- woody_richness_max,
263
- woody_richness_min,
264
- )
265
-
266
-
267
- @app.cell
268
- def _():
269
- # filtered_for_plot
270
- # filtered_flowers
271
- return
272
-
273
-
274
- @app.cell
275
- def _():
276
- #svg frame
277
- svg_width=2350
278
- svg_height=1300
279
- return svg_height, svg_width
280
-
281
-
282
- @app.cell
283
- def _(mo):
284
- mo.md(
285
- """
286
- <!-- CSS for layout of svg-->
287
- <style>
288
- svg.abc {
289
- border: 1px solid;
290
- background: #fafafa;
291
- border-radius: 4px;
292
- box-shadow: 0 1px 3px rgba(0,0,0,0.1);
293
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
294
- }
295
- .axis-label {
296
- font-size: 11px;
297
- fill: #333;
298
- }
299
- .axis-title {
300
- font-size: 13px;
301
- fill: #222;
302
- font-weight: 500;
303
- }
304
- .main-title {
305
- font-size: 20px;
306
- fill: black;
307
- font-weight: 600;
308
- }
309
-
310
- .subtitle {
311
- font-size: 11px;
312
- fill: #6b7280;
313
- font-weight: 400;
314
- }
315
-
316
- circle.nq1 {
317
- fill: #2563eb;
318
- stroke: #1e40af;
319
- stroke-width: 0.5px;
320
- opacity: 0.6;
321
- }
322
-
323
- ellipse {
324
- stroke: none;
325
- }
326
-
327
- line {
328
- stroke-linecap: round;
329
- stroke-linejoin: round;
330
- }
331
- </style>
332
- """
333
- )
334
- return
335
-
336
-
337
- @app.cell
338
- def _(mo):
339
- flower_size = mo.ui.slider(start=1, stop=2, step=0.25, value=1, label="Flower size")
340
- flower_size
341
- return (flower_size,)
342
-
343
-
344
- @app.cell
345
- def _(mo):
346
- filter_selector = mo.ui.dropdown(
347
- options=["All sites", "Top 10 yield & Bottom 10 yield"],
348
- label="Show sites"
349
- )
350
- filter_selector
351
- return (filter_selector,)
352
-
353
-
354
- @app.cell
355
- def _(
356
- Circle,
357
- Ellipse,
358
- Line,
359
- Rect,
360
- SVG,
361
- Text,
362
- bryo_richness_max,
363
- bryo_richness_min,
364
- cluster_counts,
365
- filter_selector,
366
- filtered_flowers,
367
- filtered_for_plot,
368
- flower_size,
369
- get_opacity_from_richness,
370
- herb_richness_max,
371
- herb_richness_min,
372
- math,
373
- mo,
374
- ordinal_pos,
375
- structureindex,
376
- svg_height,
377
- svg_width,
378
- woody_richness_max,
379
- woody_richness_min,
380
- ):
381
- #creating variable 'elements'
382
- _elements = []
383
-
384
- #Scaling of x-axis and y-axis
385
- margin = 90
386
- top_margin = 20 #add extra space at top for title
387
- usable_width = svg_width - 6 * margin + 30
388
- usable_height = svg_height - 2 * margin -top_margin
389
-
390
- x_min = 1
391
- x_max = 3
392
-
393
- y_min = 0
394
- y_max = 5500
395
-
396
- num_sites = len(filtered_for_plot)
397
-
398
-
399
- #===== LOOP FOR DRAWING ELEMENTS =====
400
- #adding elements to svg - loop for circles, flower petals and dashed lines of min-max yield
401
- #but instead of looping through all sites, we will loop through filtered_flowers (for selection 60 vs 20 site ids)
402
- for structure_, yield_, site_, herb_, bryo_, woody_, herb_richness, bryo_richness, woody_richness, min_y, max_y, ord_pos in zip(
403
- filtered_flowers["Coffee structure index"],
404
- filtered_flowers["Mean_CC_Yield"],
405
- filtered_flowers["Site ID"],
406
- filtered_flowers["Herb_abundance"],
407
- filtered_flowers["Bryo_abundance"],
408
- filtered_flowers["Woody_abundance"],
409
- filtered_flowers["Veg_Spps"], # Herb richness
410
- filtered_flowers["Bryo_Spps"], # Bryo richness
411
- filtered_flowers["Woody_Spps"], # Woody richness
412
- filtered_flowers["min_yield"],
413
- filtered_flowers["max_yield"],
414
- #we need to get ordinal_pos from filtered_for_plot, not filtered_flowers
415
- filtered_flowers["Site ID"].map(filtered_for_plot.set_index("Site ID")["ordinal_pos"])
416
- ):
417
-
418
- #create position for site ids to draw circles, flowers etc.
419
- cx = margin + (ord_pos/num_sites)*usable_width
420
- cy = top_margin + margin + (y_max - yield_) / (y_max - y_min) * usable_height
421
- cy_min = top_margin + margin + (y_max - min_y) / (y_max - y_min) * usable_height
422
- cy_max = top_margin + margin + (y_max - max_y) / (y_max - y_min) * usable_height
423
-
424
- #draw site ID name
425
- _elements.append(
426
- Text(x=cx, y= cy-10,
427
- text=str(site_),
428
- class_="axis-label", font_size=8)
429
- )
430
-
431
- #draw number of structure index per site ID at x-axis
432
- _elements.append(
433
- Text(x=cx-10-10, y=svg_height - margin +25,
434
- text=f"{structure_:.2f}",
435
- class_="axis-label", font_size=8,
436
- transform=f"rotate(-45, {cx-10}, {svg_height - margin +15})")
437
- )
438
-
439
- #draw circles per site ID
440
- _elements.append(
441
- Circle(
442
- cx=cx,
443
- cy=cy,
444
- r=3,
445
- class_="nq1"
446
- )
447
- )
448
-
449
-
450
- #DRAW MIN-MAX YIELD for three years - draw dashed line from min to max yield
451
- _elements.append(
452
- Line(
453
- x1=cx, y1=cy_min,
454
- x2=cx, y2=cy_max,
455
- stroke="gray",
456
- stroke_dasharray="3,3"
457
- )
458
- )
459
- # - draw small square at max yield
460
- _elements.append(
461
- Rect(x=cx-3, y=cy_max-3, width=6, height=6, fill="gray")
462
- )
463
-
464
- # - draw small square at min yield
465
- _elements.append(
466
- Rect(x=cx-3, y=cy_min-3, width=6, height=6, fill="gray")
467
- )
468
-
469
-
470
- # each petal shows LENGTH = abundance, OPACITY = richness
471
- #create three petals categories
472
- petals = [
473
- (90, herb_, "orange", herb_richness, herb_richness_min, herb_richness_max),
474
- (210, bryo_, "blue", bryo_richness, bryo_richness_min, bryo_richness_max),
475
- (330, woody_, "green", woody_richness, woody_richness_min, woody_richness_max),
476
- ]
477
-
478
- #draw ellipses based on petals data: correct direction, length corresponding abundance, opacity corresponding richness, and colour per group
479
- for angle, abundance, color, richness, min_richness, max_richness in petals:
480
- rad = math.radians(angle)
481
- petal_length = abundance / 100 * 16 * flower_size.value # scale to fit in the plot, ABUNDANCE
482
- opacity = get_opacity_from_richness(richness, min_richness, max_richness) # OPACITY = richness
483
- ex = cx + math.sin(rad) * petal_length
484
- ey = cy - math.cos(rad) * petal_length
485
- _elements.append(
486
- Ellipse(
487
- cx=ex,
488
- cy=ey,
489
- rx=3*flower_size.value,
490
- ry=petal_length,
491
- fill=color,
492
- opacity=opacity,
493
- transform=f"rotate({angle}, {ex}, {ey})"
494
- )
495
- )
496
-
497
-
498
- # ===== AXES ======
499
- #creating variable 'axes'
500
- _axes = []
501
-
502
- # X-axis: draw the line of the x-axis and label it
503
- _axes.append(
504
- Line(
505
- x1=margin,
506
- y1=svg_height - margin,
507
- x2=usable_width + margin,
508
- y2=svg_height - margin,
509
- stroke="black"
510
- )
511
- )
512
- _axes.append(
513
- Text(
514
- x= usable_width + 100,
515
- y=svg_height - margin + 22,
516
- text="Sites ordered by structure index (1-3)",
517
- class_="axis-title"
518
- )
519
- )
520
-
521
- #Add ordinal positions on X-axis
522
- for i in range(0, num_sites + 1, 1):
523
- x = margin + (i / num_sites) * usable_width
524
- _axes.append(
525
- Line(x1=x, y1=svg_height - margin, x2= x, y2=svg_height - margin - 5, stroke="black")
526
- )
527
-
528
- # ===== HISTOGRAMS PER SITE =====
529
- histogram_y = svg_height - 5
530
- bar_width = 5
531
- bar_spacing = 2 # Space between the 3 bars
532
- bar_max_height = 40
533
-
534
- _axes.append(
535
- Text(
536
- x=margin,
537
- y=histogram_y - 40,
538
- text="Cluster Distribution per Site (16 shrubs each)",
539
- class_="axis-title"
540
- )
541
- )
542
-
543
- # Colors for clusters
544
- cluster_colors = {
545
- '1': "#2d46dc",
546
- '2': "#91d76e", # Green
547
- '3': "#be2d32" # Red
548
- }
549
-
550
- # Draw histogram for each site in filtered_flowers
551
- for site_id_ in filtered_flowers['Site ID'].values:
552
- # Get ordinal position from filtered_for_plot
553
- ord_pos_val = filtered_for_plot[filtered_for_plot['Site ID'] == site_id_]['ordinal_pos'].values[0]
554
- site_x = margin + (ord_pos_val / num_sites) * usable_width
555
-
556
- # Get cluster counts for this site
557
- if site_id_ in cluster_counts.index:
558
- counts = cluster_counts.loc[site_id_, ['1', '2', '3']]
559
-
560
- # Draw 3 bars side-by-side
561
- for cluster_idx, cluster in enumerate(['1', '2', '3']):
562
- count = counts[cluster]
563
- bar_height = (count / 16) * bar_max_height
564
-
565
- # Calculate x position for each bar (3 bars side-by-side)
566
- bar_x = site_x - (bar_width + bar_spacing) + cluster_idx * (bar_width + bar_spacing)
567
-
568
- if bar_height > 0:
569
- _axes.append(
570
- Rect(
571
- x=bar_x-2.5,
572
- y=histogram_y - bar_height,
573
- width=bar_width,
574
- height=bar_height,
575
- fill=cluster_colors[cluster]
576
- )
577
- )
578
-
579
- # Y-axis: draw the line and label it
580
- _axes.append(
581
- Line(
582
- x1=margin,
583
- y1=top_margin + margin -15,
584
- x2=margin,
585
- y2=svg_height - margin,
586
- stroke="black",
587
- )
588
- )
589
-
590
- _axes.append(
591
- Text(
592
- x= margin,
593
- y= top_margin + margin -23,
594
- text="Mean coffee yield (kg/ha)",
595
- class_="axis-title"
596
- )
597
- )
598
-
599
- #Add manual arrow at top of y-axis
600
- arrow_tip_x = margin
601
- arrow_tip_y = top_margin + margin - 15
602
- _axes.append(Line(x1=arrow_tip_x, y1=arrow_tip_y, x2=arrow_tip_x - 5, y2=arrow_tip_y + 10, stroke="black"))
603
- _axes.append(Line(x1=arrow_tip_x, y1=arrow_tip_y, x2=arrow_tip_x + 5, y2=arrow_tip_y + 10, stroke="black"))
604
-
605
- #Add positions on Y-axis
606
- for val in [0, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000, 5500]:
607
-
608
- y = top_margin + margin + (y_max - val) / (y_max - y_min) * usable_height
609
-
610
- _axes.append(
611
- Line(
612
- x1=margin - 5,
613
- y1=y,
614
- x2=margin,
615
- y2=y,
616
- stroke="black"
617
- )
618
- )
619
-
620
- _axes.append(
621
- Text(
622
- x=margin -50,
623
- y=y + 5,
624
- text=str(val),
625
- class_="axis-label"
626
- )
627
- )
628
-
629
- #Add dashed reference lines for Y-axis positions
630
- # Make lines longer for 0 and 2000
631
- if val in [500, 1000, 1500, 2000]:
632
- x2_end = svg_width - 50 # Longer
633
- else:
634
- x2_end = usable_width + margin # Normal length
635
-
636
- _axes.append(
637
- Line(
638
- x1=margin,
639
- y1=y,
640
- x2=x2_end,
641
- y2=y,
642
- stroke="lightgray",
643
- stroke_dasharray="3,3",
644
- opacity=0.7
645
- )
646
- )
647
-
648
-
649
- # ===== TITLE ======
650
- _axes.append(
651
- Text(
652
- x=svg_width / 2,
653
- y= 50, # top_margin / 2 + 10,
654
- text="Exploring Coffee Yield Patterns: Structure Index, Plant Abundance, and Plant Richness",
655
- class_="main-title",
656
- text_anchor="middle"
657
- )
658
- )
659
- # Add subtitle
660
- _axes.append(
661
- Text(
662
- x=svg_width / 2,
663
- y= 75, #top_margin / 2 + 32,
664
- text="Each flower represents a site; flower petals show abundance and richness of co-occuring plant species. Min-max lines indicate yield variation across 2017-2019.",
665
- class_="subtitle",
666
- text_anchor="middle"
667
- )
668
- )
669
-
670
-
671
- # ===== LEGENDS =====
672
-
673
- # ===== RIGHT SIDE =====
674
-
675
- legend_x = usable_width + 120
676
- legend_y = top_margin + margin
677
-
678
- # ===== PART A: PLANT SPECIES LEGENDS =====
679
-
680
- # ===== 1) PLANT SPECIES TYPE =====
681
- _axes.append(
682
- Text(
683
- x=legend_x,
684
- y=legend_y,
685
- text="Plant Species Type",
686
- class_="axis-title"
687
- )
688
- )
689
-
690
- legend_colors = [
691
- ("orange", "Herbaceous plant species"),
692
- ("blue", "Bryophyte plant species"),
693
- ("green", "Woody plant species"),
694
- ]
695
-
696
- for i, (color, label) in enumerate(legend_colors):
697
- y_pos = legend_y + 20 + i * 18
698
- _axes.append(
699
- Ellipse(cx=legend_x, cy=y_pos, rx=5, ry=5, fill=color, opacity=0.6)
700
- )
701
- _axes.append(
702
- Text(x=legend_x + 15, y=y_pos + 4, text=label, class_="axis-label")
703
- )
704
-
705
- # ===== 2) PETAL LENGTH = ABUNDANCE =====
706
- legend_y_abundance = legend_y + 110
707
-
708
- _axes.append(
709
- Text(
710
- x=legend_x,
711
- y=legend_y_abundance,
712
- text="Petal Length = Plant Abundance",
713
- class_="axis-title"
714
- )
715
- )
716
-
717
- _axes.append(
718
- Text(
719
- x=legend_x,
720
- y=legend_y_abundance + 16,
721
- text="(% of plant community)",
722
- class_="axis-label",
723
- font_size=8
724
- )
725
- )
726
-
727
- # 5 petals showing abundance gradient with actual percentage values
728
- abundance_values = [0, 25, 50, 75, 100]
729
- petal_lengths = [2, 6, 10, 14, 18]
730
- spacing = 50
731
-
732
- for i, (abundance, petal_len) in enumerate(zip(abundance_values, petal_lengths)):
733
- ex = legend_x + 5 + i * spacing
734
- ey = legend_y_abundance + 40
735
- _axes.append(
736
- Ellipse(
737
- cx=ex,
738
- cy=ey,
739
- rx=1.5,
740
- ry=petal_len,
741
- fill="gray",
742
- opacity=0.3,
743
- transform=f"rotate(90, {ex}, {ey})"
744
- )
745
- )
746
-
747
- # Add value labels below
748
- _axes.append(
749
- Text(x=ex - 5, y=legend_y_abundance + 62, text=f"{abundance}%",
750
- class_="axis-label", font_size=7)
751
- )
752
-
753
- # ===== 3) PETAL OPACITY = SPECIES RICHNESS =====
754
- legend_y_richness = legend_y_abundance + 110
755
-
756
- _axes.append(
757
- Text(
758
- x=legend_x,
759
- y=legend_y_richness,
760
- text="Petal Opacity = Species Richness",
761
- class_="axis-title"
762
- )
763
- )
764
-
765
- _axes.append(
766
- Text(
767
- x=legend_x,
768
- y=legend_y_richness + 16,
769
- text="(normalized 0.2-1.0 scale)",
770
- class_="axis-label",
771
- font_size=8
772
- )
773
- )
774
-
775
- # 5 circles showing richness gradient with actual species counts
776
- richness_values = [
777
- (herb_richness_min, f"{int(herb_richness_min)} sp."),
778
- ((herb_richness_min + herb_richness_max) * 0.25, f"{int((herb_richness_min + herb_richness_max) * 0.25)} sp."),
779
- ((herb_richness_min + herb_richness_max) * 0.5, f"{int((herb_richness_min + herb_richness_max) * 0.5)} sp."),
780
- ((herb_richness_min + herb_richness_max) * 0.75, f"{int((herb_richness_min + herb_richness_max) * 0.75)} sp."),
781
- (herb_richness_max, f"{int(herb_richness_max)} sp."),
782
- ]
783
-
784
- opacities_richness = [0.2, 0.4, 0.6, 0.8, 1.0]
785
-
786
- for i, (opacity, (richness_val, richness_label)) in enumerate(zip(opacities_richness, richness_values)):
787
- ex = legend_x + 5 + i * spacing
788
- ey = legend_y_richness + 40
789
- _axes.append(
790
- Ellipse(cx=ex, cy=ey, rx=5, ry=5, fill="gray", opacity=opacity)
791
- )
792
-
793
- # Add value labels below
794
- _axes.append(
795
- Text(x=ex - 8, y=legend_y_richness + 62, text=richness_label,
796
- class_="axis-label", font_size=7)
797
- )
798
-
799
-
800
- # Frame around three Plant Species legends (Type, Abundance, Richness)
801
- frame_padding = 12
802
- _axes.append(
803
- Rect(
804
- x=legend_x - frame_padding,
805
- y=legend_y - frame_padding,
806
- width=320,
807
- height=legend_y_richness + 100 - (legend_y - frame_padding),
808
- fill="none",
809
- stroke="#cccccc",
810
- stroke_width=1.5,
811
- opacity=0.9
812
- )
813
- )
814
-
815
- # ===== STRUCTURE INDEX DENSITY LEGEND =====
816
- density_legend_y = legend_y_richness + 145
817
-
818
- #add title
819
- _axes.append(
820
- Text(
821
- x=legend_x,
822
- y=density_legend_y - 15,
823
- text="Structure Index Density",
824
- class_="axis-title"
825
- )
826
- )
827
-
828
- # Create a vertical gradient scale showing gap size progression
829
- gap_values = ["gap ≈ 0", "gap < 0.03", "gap < 0.06", "gap < 0.10", "gap ≥ 0.10"]
830
- opacity_values = [0.35, 0.32, 0.25, 0.18, 0.10]
831
-
832
- # Top label - High density
833
- _axes.append(
834
- Text(x=legend_x + 30, y=density_legend_y, text="High density (compressed)",
835
- class_="axis-label", font_size=9)
836
- )
837
-
838
- # Draw rectangles vertically
839
- for i, (gap, opacity) in enumerate(zip(gap_values, opacity_values)):
840
- y_pos = density_legend_y + 10 + i * 22
841
-
842
- _axes.append(
843
- Rect(x=legend_x, y=y_pos, width=20, height=18, fill="gray", opacity=opacity)
844
- )
845
-
846
- _axes.append(
847
- Text(x=legend_x + 28, y=y_pos + 13, text=gap,
848
- class_="axis-label", font_size=9)
849
- )
850
-
851
- # Bottom label - Low density
852
- _axes.append(
853
- Text(x=legend_x + 30, y=density_legend_y + 10 + 5 * 22 + 15,
854
- text="Low density (spread)", class_="axis-label", font_size=9)
855
- )
856
-
857
- # Frame around Structure Index Density legend
858
- _axes.append(
859
- Rect(
860
- x=legend_x - frame_padding,
861
- y= 430, #density_legend_y - frame_padding,
862
- width=320,
863
- height=5 * 22 + 60 +15,
864
- fill="none",
865
- stroke="#cccccc",
866
- stroke_width=1.5,
867
- opacity=0.9
868
- )
869
- )
870
-
871
-
872
- # ===== CLUSTER LEGEND =====
873
- cluster_legend_x = usable_width + 350
874
- cluster_legend_y = histogram_y - 63
875
-
876
- _axes.append(
877
- Text(
878
- x=cluster_legend_x -143,
879
- y=cluster_legend_y +43,
880
- text="Cluster Distribution",
881
- class_="axis-title"
882
- )
883
- )
884
-
885
- cluster_dataa = [
886
- ("#2d46dc", "Cluster 1"),
887
- ("#91d76e", "Cluster 2"),
888
- ("#be2d32", "Cluster 3"),
889
- ]
890
-
891
- for i, (color, label) in enumerate(cluster_dataa):
892
- y_pos = cluster_legend_y + 16 + i * 16
893
- _axes.append(
894
- Rect(x=cluster_legend_x, y=y_pos, width=10, height=10, fill=color)
895
- )
896
- _axes.append(
897
- Text(x=cluster_legend_x + 18, y=y_pos + 10, text=label, class_="axis-label")
898
- )
899
-
900
-
901
-
902
- # ===== AGGREGATE FLOWERS (Bottom right area) =====
903
-
904
- #create two groups
905
- top_half = filtered_flowers.nlargest(len(filtered_flowers)//2, "Mean_CC_Yield")
906
- bottom_half = filtered_flowers.nsmallest(len(filtered_flowers)//2, "Mean_CC_Yield")
907
-
908
- # ABUNDANCE (for petal length)
909
- g1_herb = bottom_half["Herb_abundance"].mean()
910
- g1_bryo = bottom_half["Bryo_abundance"].mean()
911
- g1_woody = bottom_half["Woody_abundance"].mean()
912
-
913
- g2_herb = top_half["Herb_abundance"].mean()
914
- g2_bryo = top_half["Bryo_abundance"].mean()
915
- g2_woody = top_half["Woody_abundance"].mean()
916
-
917
- # RICHNESS (for petal opacity)
918
- g1_herb_richness = bottom_half["Veg_Spps"].mean()
919
- g1_bryo_richness = bottom_half["Bryo_Spps"].mean()
920
- g1_woody_richness = bottom_half["Woody_Spps"].mean()
921
-
922
- g2_herb_richness = top_half["Veg_Spps"].mean()
923
- g2_bryo_richness = top_half["Bryo_Spps"].mean()
924
- g2_woody_richness = top_half["Woody_Spps"].mean()
925
-
926
- #y positions fixed to mean yield of each group
927
- flower_x = usable_width + 200
928
- flower_y1 = top_margin + margin + (y_max - bottom_half["Mean_CC_Yield"].mean()) / (y_max - y_min) * usable_height #+800
929
- flower_y2 = top_margin + margin + (y_max - top_half["Mean_CC_Yield"].mean()) / (y_max - y_min) * usable_height # + 900
930
-
931
- #define draw_flower mentioning position, direction, abundance for two groups, colour etc
932
- def draw_flower(cx, cy, herb, bryo, woody, herb_rich, bryo_rich, woody_rich, scale=1):
933
- petals = [
934
- (90, herb, "orange", herb_rich, herb_richness_min, herb_richness_max),
935
- (210, bryo, "blue", bryo_rich, bryo_richness_min, bryo_richness_max),
936
- (330, woody, "green", woody_rich, woody_richness_min, woody_richness_max),
937
- ]
938
- flower_elements = []
939
- for angle, abundance, color, richness, min_richness, max_richness in petals:
940
- rad = math.radians(angle)
941
- petal_length = abundance / 100 * 14 * scale
942
- opacity = get_opacity_from_richness(richness, min_richness, max_richness)
943
- ex = cx + math.sin(rad) * petal_length
944
- ey = cy - math.cos(rad) * petal_length
945
- flower_elements.append(
946
- Ellipse(
947
- cx=ex,
948
- cy=ey,
949
- rx=3 * scale,
950
- ry=petal_length,
951
- fill=color,
952
- opacity=opacity,
953
- transform=f"rotate({angle}, {ex}, {ey})"
954
- )
955
- )
956
- return flower_elements
957
-
958
- # draw both aggregate flowers using definition
959
- _elements += draw_flower(flower_x, flower_y1, g1_herb, g1_bryo, g1_woody, g1_herb_richness, g1_bryo_richness, g1_woody_richness, scale=3)
960
- _elements += draw_flower(flower_x, flower_y2, g2_herb, g2_bryo, g2_woody, g2_herb_richness, g2_bryo_richness, g2_woody_richness, scale=3)
961
-
962
- #add labels
963
- _axes.append(
964
- Text(
965
- x=legend_x#flower_x-60
966
- , y=density_legend_y +235,
967
- text="Aggregate flowers of two groups comparing low/high yield",
968
- class_="axis-title"#,
969
- #font_size=6
970
- )
971
- )
972
- _axes.append(Text(
973
- x=legend_x #flower_x-60
974
- , y=flower_y1 - 60,
975
- text="Sites with low yield (Lower half of 60 sites/Bottom 10)", class_="axis-label"#, font_size=7
976
- ))
977
- _axes.append(Text(
978
- x=legend_x,
979
- #flower_x-60,
980
- y=flower_y2 -60,
981
- text="Sites with top yield (Upper half of 60 sites/Top 10)", class_="axis-label"#, font_size=7
982
- ))
983
-
984
- # ===== DENSITY VISUALISATION BACKGROUND =====
985
- #add values of structure index in a list to calculate gaps
986
- struct_values = structureindex.values
987
-
988
- for idx in range(len(struct_values) - 1):
989
- gap = struct_values[idx + 1] - struct_values[idx]
990
-
991
- #size of gap determines opacity
992
- if gap == 0.0000:
993
- opacity = 0.35
994
- elif gap < 0.03:
995
- opacity = 0.32
996
- elif gap < 0.06:
997
- opacity = 0.25
998
- elif gap < 0.10:
999
- opacity = 0.18
1000
- else:
1001
- opacity = 0.10
1002
-
1003
- #define positions for drawing rectangle (in between sites)
1004
- x_curr = margin + (ordinal_pos[idx] / num_sites) * usable_width
1005
- x_next = margin + (ordinal_pos[idx + 1] / num_sites) * usable_width
1006
-
1007
- #draw rectangles between each site/structure index value, that span across the whole y-axis, using opacity variable to change according to gap size
1008
- _axes.append(
1009
- Rect(x=x_curr, y=margin+ top_margin, width=x_next - x_curr,
1010
- height=usable_height, fill="gray", opacity=opacity)
1011
- )
1012
-
1013
- # ===== CREATING SVG FRAME =====
1014
- _svg = SVG(width=svg_width, height=svg_height, class_="abc",
1015
- elements=_elements+_axes)
1016
- svg_str = _svg.as_str()
1017
-
1018
- mo.vstack([
1019
- mo.Html(svg_str),
1020
- mo.hstack([
1021
- filter_selector,
1022
- flower_size
1023
- ])
1024
- ])
1025
- return (
1026
- abundance,
1027
- abundance_values,
1028
- angle,
1029
- arrow_tip_x,
1030
- arrow_tip_y,
1031
- bar_height,
1032
- bar_max_height,
1033
- bar_spacing,
1034
- bar_width,
1035
- bar_x,
1036
- bottom_half,
1037
- bryo_,
1038
- bryo_richness,
1039
- cluster,
1040
- cluster_colors,
1041
- cluster_dataa,
1042
- cluster_idx,
1043
- cluster_legend_x,
1044
- cluster_legend_y,
1045
- color,
1046
- count,
1047
- counts,
1048
- cx,
1049
- cy,
1050
- cy_max,
1051
- cy_min,
1052
- density_legend_y,
1053
- draw_flower,
1054
- ex,
1055
- ey,
1056
- flower_x,
1057
- flower_y1,
1058
- flower_y2,
1059
- frame_padding,
1060
- g1_bryo,
1061
- g1_bryo_richness,
1062
- g1_herb,
1063
- g1_herb_richness,
1064
- g1_woody,
1065
- g1_woody_richness,
1066
- g2_bryo,
1067
- g2_bryo_richness,
1068
- g2_herb,
1069
- g2_herb_richness,
1070
- g2_woody,
1071
- g2_woody_richness,
1072
- gap,
1073
- gap_values,
1074
- herb_,
1075
- herb_richness,
1076
- histogram_y,
1077
- i,
1078
- idx,
1079
- label,
1080
- legend_colors,
1081
- legend_x,
1082
- legend_y,
1083
- legend_y_abundance,
1084
- legend_y_richness,
1085
- margin,
1086
- max_richness,
1087
- max_y,
1088
- min_richness,
1089
- min_y,
1090
- num_sites,
1091
- opacities_richness,
1092
- opacity,
1093
- opacity_values,
1094
- ord_pos,
1095
- ord_pos_val,
1096
- petal_len,
1097
- petal_length,
1098
- petal_lengths,
1099
- petals,
1100
- rad,
1101
- richness,
1102
- richness_label,
1103
- richness_val,
1104
- richness_values,
1105
- site_,
1106
- site_id_,
1107
- site_x,
1108
- spacing,
1109
- struct_values,
1110
- structure_,
1111
- svg_str,
1112
- top_half,
1113
- top_margin,
1114
- usable_height,
1115
- usable_width,
1116
- val,
1117
- woody_,
1118
- woody_richness,
1119
- x,
1120
- x2_end,
1121
- x_curr,
1122
- x_max,
1123
- x_min,
1124
- x_next,
1125
- y,
1126
- y_max,
1127
- y_min,
1128
- y_pos,
1129
- yield_,
1130
- )
1131
-
1132
-
1133
- if __name__ == "__main__":
1134
- app.run()
 
1
+ import marimo
2
+
3
+ __generated_with = "0.11.26"
4
+ app = marimo.App(width="medium")
5
+
6
+
7
+ @app.cell
8
+ def _():
9
+ import marimo as mo
10
+ import pandas as pd
11
+ import math
12
+ from svg import SVG, Circle, Text, G, Line, Ellipse, Rect, Title
13
+ import numpy as np
14
+ return Circle, Ellipse, G, Line, Rect, SVG, Text, Title, math, mo, np, pd
15
+
16
+
17
+ @app.cell
18
+ def _(pd):
19
+ # ===== IMPORT DATASETS =====
20
+ coffeeyield = pd.read_excel("data/Coffee_yield.xlsx")
21
+ coffeestructureindex_management = pd.read_excel("data/Environmental_and_management_variables.xlsx")
22
+ plant_species_richness = pd.read_excel("data/Plant_species_richness.xlsx")
23
+ return coffeestructureindex_management, coffeeyield, plant_species_richness
24
+
25
+
26
+ @app.cell
27
+ def _(pd):
28
+ # ===== PREPARE WOODY DATA =====
29
+
30
+ #Load the excelfile
31
+ woody_species_abundance = pd.read_excel("data/Woody_species_abundance.xlsx")
32
+ woody_species_abundance
33
+
34
+ #Creating dataframe of total abundance of woody species, per Site ID
35
+ woody_totals = woody_species_abundance.iloc[:, 1:].sum().reset_index()
36
+
37
+ #Rename the columns to meaningful names
38
+ woody_totals.columns = ["Site ID", "Woody_total"]
39
+
40
+ #Normalise the abundance values to 0-100 scale for comparability
41
+ #Divide each value by max (0-1 scale) and multiply by 100 (0-100 scale)
42
+ woody_totals["Woody_abundance"] = (woody_totals["Woody_total"] / woody_totals["Woody_total"].max()) * 100
43
+
44
+ #Keep only the Site ID and normalised abundance columns
45
+ w_abundance = woody_totals[["Site ID", "Woody_abundance"]]
46
+ #w_abundance
47
+ return w_abundance, woody_species_abundance, woody_totals
48
+
49
+
50
+ @app.cell
51
+ def _(pd):
52
+ # ===== PREPARE BRYOPHYTE DATA =====
53
+
54
+ #Load the txtfile
55
+ bryophyte_species_abundance = pd.read_csv("data/Bryophyte_frequency.txt", sep="\t")
56
+
57
+ #Creating dataframe of total abundance of bryo species, per Site ID
58
+ bryo_totals = bryophyte_species_abundance.iloc[:, 1:].sum().reset_index()
59
+
60
+ #Rename the columns to meaningful names
61
+ bryo_totals.columns = ["Site ID", "Bryo_total"]
62
+
63
+ #Normalise the abundance values to 0-100 scale for comparability
64
+ #Divide each value by max (0-1 scale) and multiply by 100 (0-100 scale)
65
+ bryo_totals["Bryo_abundance"] = (bryo_totals["Bryo_total"] / bryo_totals["Bryo_total"].max()) * 100
66
+
67
+ #Keep only the Site ID and normalised abundance columns
68
+ b_abundance = bryo_totals[["Site ID", "Bryo_abundance"]]
69
+ #b_abundance
70
+ return b_abundance, bryo_totals, bryophyte_species_abundance
71
+
72
+
73
+ @app.cell(hide_code=True)
74
+ def _():
75
+ # # ===== VERIFY BRYOPHYTE DATA =====
76
+
77
+ # # See the raw totals BEFORE normalization
78
+ # print("Raw bryophyte totals (before normalization):")
79
+ # print(bryo_totals[["Site ID", "Bryo_total"]])
80
+
81
+ # # See which site has the max
82
+ # print(f"\nMax bryo total: {bryo_totals['Bryo_total'].max()}")
83
+
84
+ # # Check a specific site (e.g., Ge1)
85
+ # ge1_row = bryo_totals[bryo_totals["Site ID"] == "Ge1"]
86
+ # if not ge1_row.empty:
87
+ # ge1_raw = ge1_row["Bryo_total"].values[0]
88
+ # print(f"Ge1 raw total: {ge1_raw}")
89
+
90
+ # # Verify the normalization calculation manually
91
+ # ge1_normalized_manual = (ge1_raw / bryo_totals["Bryo_total"].max()) * 100
92
+ # ge1_normalized_actual = ge1_row["Bryo_abundance"].values[0]
93
+
94
+ # print(f"Ge1 normalized (manual calc): {ge1_normalized_manual:.2f}")
95
+ # print(f"Ge1 normalized (from data): {ge1_normalized_actual:.2f}")
96
+ # print(f"Match: {abs(ge1_normalized_manual - ge1_normalized_actual) < 0.01}")
97
+ # else:
98
+ # print("Ge1 not found in data")
99
+
100
+ # # Show distribution
101
+ # print(f"\nBryo abundance range: {bryo_totals['Bryo_abundance'].min():.2f} to {bryo_totals['Bryo_abundance'].max():.2f}")
102
+
103
+ # # Display final result
104
+ # print("\nFinal bryophyte abundance (0-100 scale):")
105
+ # print(b_abundance.head(10))
106
+ return
107
+
108
+
109
+ @app.cell
110
+ def _(pd):
111
+ # ===== PREPARE HERB DATA =====
112
+
113
+ #Load the txtfile
114
+ herb_species_abundance = pd.read_csv("data/Herbaceous_vegetation_Abundance.txt", sep="\t")
115
+
116
+ #Set Site ID as index and then sum species columns for total abundance
117
+ herb_totals = herb_species_abundance.set_index(herb_species_abundance.columns[0]).iloc[:, :].sum(axis=1).reset_index()
118
+
119
+ #Rename the columns to meaningful names
120
+ herb_totals.columns = ["Site ID", "Herb_total"]
121
+
122
+ #Normalise the abundance values to 0-100 scale for comparability
123
+ #Divide each value by max (0-1 scale) and multiply by 100 (0-100 scale)
124
+ herb_totals["Herb_abundance"] = (herb_totals["Herb_total"] / herb_totals["Herb_total"].max()) * 100
125
+ herb_totals
126
+
127
+ #Keep only the Site ID and normalised abundance columns
128
+ h_abundance = herb_totals[["Site ID", "Herb_abundance"]]
129
+ #h_abundance
130
+ return h_abundance, herb_species_abundance, herb_totals
131
+
132
+
133
+ @app.cell
134
+ def _(
135
+ b_abundance,
136
+ coffeestructureindex_management,
137
+ coffeeyield,
138
+ h_abundance,
139
+ plant_species_richness,
140
+ w_abundance,
141
+ ):
142
+ merged = coffeeyield \
143
+ .merge(coffeestructureindex_management, on="Site ID") \
144
+ .merge(plant_species_richness, on="Site ID") \
145
+ .merge(w_abundance, on="Site ID")\
146
+ .merge(b_abundance, on="Site ID")\
147
+ .merge(h_abundance, on="Site ID")
148
+ #merged
149
+ return (merged,)
150
+
151
+
152
+ @app.cell
153
+ def _(filtered_flowers, filtered_for_plot, pd):
154
+ # ===== PREPARE CLUSTER DATA FOR HISTOGRAMS =====
155
+ cluster_data = pd.read_excel("data/Coffee_structure_index_variables.xlsx")
156
+
157
+ # Simple: group by Site ID and cluster, count rows
158
+ cluster_counts = cluster_data.groupby(['Site ID', 'Fitted cluster']).size().unstack(fill_value=0)
159
+
160
+ # Make sure we have columns 1, 2, 3 (add if missing)
161
+ for col in [1, 2, 3]:
162
+ if col not in cluster_counts.columns:
163
+ cluster_counts[col] = 0
164
+
165
+ # Keep only sites we're showing
166
+ cluster_counts = cluster_counts[cluster_counts.index.isin(filtered_flowers['Site ID'])]
167
+
168
+ # Sort to match graph order
169
+ site_order = filtered_for_plot[filtered_for_plot['Site ID'].isin(cluster_counts.index)].set_index('Site ID')
170
+ cluster_counts = cluster_counts.loc[site_order.index]
171
+
172
+ # FIX: Rename integer columns to strings
173
+ cluster_counts.columns = cluster_counts.columns.astype(str)
174
+
175
+ #cluster_counts
176
+ return cluster_counts, cluster_data, col, site_order
177
+
178
+
179
+ @app.cell
180
+ def _(filter_selector, merged, pd):
181
+ # ===== PREPARE DATA FOR VISUALISATION. =====
182
+
183
+ # ===== CREATING TWO VARIABLES FOR SELECTOR: one for plotting whole graph, one for filtering flowers only =====
184
+
185
+ #Determine which sites to display (all variables for axis/background)
186
+ filtered_for_plot = merged.copy()
187
+ filtered_for_plot = filtered_for_plot.sort_values("Coffee structure index").reset_index(drop=True)
188
+ filtered_for_plot["ordinal_pos"] = range(1, len(filtered_for_plot) + 1)
189
+
190
+ # Define min/max yield for ALL sites (needed for axes)
191
+ filtered_for_plot["min_yield"] = filtered_for_plot[["CC_Yield_2017", "CC_Yield_2018", "CC_Yield_2019"]].min(axis=1, skipna=True)
192
+ filtered_for_plot["max_yield"] = filtered_for_plot[["CC_Yield_2017", "CC_Yield_2018", "CC_Yield_2019"]].max(axis=1, skipna=True)
193
+
194
+ #Determine which flowers are shown (changes based on filter)
195
+ if filter_selector.value == "All sites":
196
+ filtered_flowers = filtered_for_plot.copy()
197
+ show_labels = False
198
+ else: # "Top 10 + Bottom 10 yield"
199
+ t10 = merged.nlargest(10, "Mean_CC_Yield")
200
+ b10 = merged.nsmallest(10, "Mean_CC_Yield")
201
+ filtered_flowers = pd.concat([t10, b10]).sort_values("Coffee structure index").reset_index(drop=True)
202
+ show_labels = True
203
+
204
+ # Add ordinal_pos, min_yield, max_yield from filtered_for_plot + add if to avoid duplicates (every time code runs)
205
+ if "ordinal_pos" not in filtered_flowers.columns:
206
+ filtered_flowers = filtered_flowers.merge(
207
+ filtered_for_plot[["Site ID", "ordinal_pos", "min_yield", "max_yield"]],
208
+ on="Site ID",
209
+ how="left"
210
+ )
211
+
212
+ # ===== PREPERATION OF RICHNESS VARIABLE: CALCULATE MIN/MAX RICHNESS FOR NORMALIZATION =====
213
+ herb_richness_min = filtered_flowers["Veg_Spps"].min()
214
+ herb_richness_max = filtered_flowers["Veg_Spps"].max()
215
+ bryo_richness_min = filtered_flowers["Bryo_Spps"].min()
216
+ bryo_richness_max = filtered_flowers["Bryo_Spps"].max()
217
+ woody_richness_min = filtered_flowers["Woody_Spps"].min()
218
+ woody_richness_max = filtered_flowers["Woody_Spps"].max()
219
+
220
+ # Function to normalize richness and convert to opacity in petals
221
+ def get_opacity_from_richness(value, min_val, max_val):
222
+ if max_val == min_val: # Handle case where all values are the same
223
+ normalized = 0.5
224
+ else:
225
+ normalized = (value - min_val) / (max_val - min_val)
226
+ return 0.2 + (normalized * 0.8) # Maps to 0.2-1.0 opacity range
227
+
228
+
229
+ # ===== EXTRACT VARIABLES for plotting ======
230
+ structureindex = filtered_for_plot["Coffee structure index"]
231
+ mean_coffee_yield = filtered_for_plot["Mean_CC_Yield"]
232
+ site_id = filtered_for_plot["Site ID"]
233
+ herb_abundance = filtered_for_plot["Herb_abundance"]
234
+ bryo_abundance = filtered_for_plot["Bryo_abundance"]
235
+ woody_abundance = filtered_for_plot["Woody_abundance"]
236
+ ordinal_pos = filtered_for_plot["ordinal_pos"]
237
+
238
+ #Extract variables for flowers (filtered)
239
+ flower_sites = filtered_flowers["Site ID"].tolist()
240
+
241
+ print(f"All sites to display: {len(filtered_for_plot)}")
242
+ print(f"Flowers to show: {len(filtered_flowers)}")
243
+ return (
244
+ b10,
245
+ bryo_abundance,
246
+ bryo_richness_max,
247
+ bryo_richness_min,
248
+ filtered_flowers,
249
+ filtered_for_plot,
250
+ flower_sites,
251
+ get_opacity_from_richness,
252
+ herb_abundance,
253
+ herb_richness_max,
254
+ herb_richness_min,
255
+ mean_coffee_yield,
256
+ ordinal_pos,
257
+ show_labels,
258
+ site_id,
259
+ structureindex,
260
+ t10,
261
+ woody_abundance,
262
+ woody_richness_max,
263
+ woody_richness_min,
264
+ )
265
+
266
+
267
+ @app.cell
268
+ def _():
269
+ # filtered_for_plot
270
+ # filtered_flowers
271
+ return
272
+
273
+
274
+ @app.cell
275
+ def _():
276
+ #svg frame
277
+ svg_width=2350
278
+ svg_height=1300
279
+ return svg_height, svg_width
280
+
281
+
282
+ @app.cell
283
+ def _(mo):
284
+ mo.md(
285
+ """
286
+ <!-- CSS for layout of svg-->
287
+ <style>
288
+ svg.abc {
289
+ border: 1px solid;
290
+ background: #fafafa;
291
+ border-radius: 4px;
292
+ box-shadow: 0 1px 3px rgba(0,0,0,0.1);
293
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
294
+ }
295
+ .axis-label {
296
+ font-size: 11px;
297
+ fill: #333;
298
+ }
299
+ .axis-title {
300
+ font-size: 13px;
301
+ fill: #222;
302
+ font-weight: 500;
303
+ }
304
+ .main-title {
305
+ font-size: 20px;
306
+ fill: black;
307
+ font-weight: 600;
308
+ }
309
+
310
+ .subtitle {
311
+ font-size: 11px;
312
+ fill: #6b7280;
313
+ font-weight: 400;
314
+ }
315
+
316
+ circle.nq1 {
317
+ fill: #2563eb;
318
+ stroke: #1e40af;
319
+ stroke-width: 0.5px;
320
+ opacity: 0.6;
321
+ }
322
+
323
+ ellipse {
324
+ stroke: none;
325
+ }
326
+
327
+ line {
328
+ stroke-linecap: round;
329
+ stroke-linejoin: round;
330
+ }
331
+ </style>
332
+ """
333
+ )
334
+ return
335
+
336
+
337
+ @app.cell
338
+ def _(mo):
339
+ flower_size = mo.ui.slider(start=1, stop=2, step=0.25, value=1, label="Flower size")
340
+ #flower_size
341
+ return (flower_size,)
342
+
343
+
344
+ @app.cell
345
+ def _(mo):
346
+ filter_selector = mo.ui.dropdown(
347
+ options=["All sites", "Top 10 yield & Bottom 10 yield"],
348
+ label="Show sites"
349
+ )
350
+ #filter_selector
351
+ return (filter_selector,)
352
+
353
+
354
+ @app.cell
355
+ def _(
356
+ Circle,
357
+ Ellipse,
358
+ Line,
359
+ Rect,
360
+ SVG,
361
+ Text,
362
+ bryo_richness_max,
363
+ bryo_richness_min,
364
+ cluster_counts,
365
+ filter_selector,
366
+ filtered_flowers,
367
+ filtered_for_plot,
368
+ flower_size,
369
+ get_opacity_from_richness,
370
+ herb_richness_max,
371
+ herb_richness_min,
372
+ math,
373
+ mo,
374
+ ordinal_pos,
375
+ structureindex,
376
+ svg_height,
377
+ svg_width,
378
+ woody_richness_max,
379
+ woody_richness_min,
380
+ ):
381
+ #creating variable 'elements'
382
+ _elements = []
383
+
384
+ #Scaling of x-axis and y-axis
385
+ margin = 90
386
+ top_margin = 20 #add extra space at top for title
387
+ usable_width = svg_width - 6 * margin + 30
388
+ usable_height = svg_height - 2 * margin -top_margin
389
+
390
+ x_min = 1
391
+ x_max = 3
392
+
393
+ y_min = 0
394
+ y_max = 5500
395
+
396
+ num_sites = len(filtered_for_plot)
397
+
398
+
399
+ #===== LOOP FOR DRAWING ELEMENTS =====
400
+ #adding elements to svg - loop for circles, flower petals and dashed lines of min-max yield
401
+ #but instead of looping through all sites, we will loop through filtered_flowers (for selection 60 vs 20 site ids)
402
+ for structure_, yield_, site_, herb_, bryo_, woody_, herb_richness, bryo_richness, woody_richness, min_y, max_y, ord_pos in zip(
403
+ filtered_flowers["Coffee structure index"],
404
+ filtered_flowers["Mean_CC_Yield"],
405
+ filtered_flowers["Site ID"],
406
+ filtered_flowers["Herb_abundance"],
407
+ filtered_flowers["Bryo_abundance"],
408
+ filtered_flowers["Woody_abundance"],
409
+ filtered_flowers["Veg_Spps"], # Herb richness
410
+ filtered_flowers["Bryo_Spps"], # Bryo richness
411
+ filtered_flowers["Woody_Spps"], # Woody richness
412
+ filtered_flowers["min_yield"],
413
+ filtered_flowers["max_yield"],
414
+ #we need to get ordinal_pos from filtered_for_plot, not filtered_flowers
415
+ filtered_flowers["Site ID"].map(filtered_for_plot.set_index("Site ID")["ordinal_pos"])
416
+ ):
417
+
418
+ #create position for site ids to draw circles, flowers etc.
419
+ cx = margin + (ord_pos/num_sites)*usable_width
420
+ cy = top_margin + margin + (y_max - yield_) / (y_max - y_min) * usable_height
421
+ cy_min = top_margin + margin + (y_max - min_y) / (y_max - y_min) * usable_height
422
+ cy_max = top_margin + margin + (y_max - max_y) / (y_max - y_min) * usable_height
423
+
424
+ #draw site ID name
425
+ _elements.append(
426
+ Text(x=cx, y= cy-10,
427
+ text=str(site_),
428
+ class_="axis-label", font_size=8)
429
+ )
430
+
431
+ #draw number of structure index per site ID at x-axis
432
+ _elements.append(
433
+ Text(x=cx-10-10, y=svg_height - margin +25,
434
+ text=f"{structure_:.2f}",
435
+ class_="axis-label", font_size=8,
436
+ transform=f"rotate(-45, {cx-10}, {svg_height - margin +15})")
437
+ )
438
+
439
+ #draw circles per site ID
440
+ _elements.append(
441
+ Circle(
442
+ cx=cx,
443
+ cy=cy,
444
+ r=3,
445
+ class_="nq1"
446
+ )
447
+ )
448
+
449
+
450
+ #DRAW MIN-MAX YIELD for three years - draw dashed line from min to max yield
451
+ _elements.append(
452
+ Line(
453
+ x1=cx, y1=cy_min,
454
+ x2=cx, y2=cy_max,
455
+ stroke="gray",
456
+ stroke_dasharray="3,3"
457
+ )
458
+ )
459
+ # - draw small square at max yield
460
+ _elements.append(
461
+ Rect(x=cx-3, y=cy_max-3, width=6, height=6, fill="gray")
462
+ )
463
+
464
+ # - draw small square at min yield
465
+ _elements.append(
466
+ Rect(x=cx-3, y=cy_min-3, width=6, height=6, fill="gray")
467
+ )
468
+
469
+
470
+ # each petal shows LENGTH = abundance, OPACITY = richness
471
+ #create three petals categories
472
+ petals = [
473
+ (90, herb_, "orange", herb_richness, herb_richness_min, herb_richness_max),
474
+ (210, bryo_, "blue", bryo_richness, bryo_richness_min, bryo_richness_max),
475
+ (330, woody_, "green", woody_richness, woody_richness_min, woody_richness_max),
476
+ ]
477
+
478
+ #draw ellipses based on petals data: correct direction, length corresponding abundance, opacity corresponding richness, and colour per group
479
+ for angle, abundance, color, richness, min_richness, max_richness in petals:
480
+ rad = math.radians(angle)
481
+ petal_length = abundance / 100 * 16 * flower_size.value # scale to fit in the plot, ABUNDANCE
482
+ opacity = get_opacity_from_richness(richness, min_richness, max_richness) # OPACITY = richness
483
+ ex = cx + math.sin(rad) * petal_length
484
+ ey = cy - math.cos(rad) * petal_length
485
+ _elements.append(
486
+ Ellipse(
487
+ cx=ex,
488
+ cy=ey,
489
+ rx=3*flower_size.value,
490
+ ry=petal_length,
491
+ fill=color,
492
+ opacity=opacity,
493
+ transform=f"rotate({angle}, {ex}, {ey})"
494
+ )
495
+ )
496
+
497
+
498
+ # ===== AXES ======
499
+ #creating variable 'axes'
500
+ _axes = []
501
+
502
+ # X-axis: draw the line of the x-axis and label it
503
+ _axes.append(
504
+ Line(
505
+ x1=margin,
506
+ y1=svg_height - margin,
507
+ x2=usable_width + margin,
508
+ y2=svg_height - margin,
509
+ stroke="black"
510
+ )
511
+ )
512
+ _axes.append(
513
+ Text(
514
+ x= usable_width + 100,
515
+ y=svg_height - margin + 22,
516
+ text="Sites ordered by structure index (1-3)",
517
+ class_="axis-title"
518
+ )
519
+ )
520
+
521
+ #Add ordinal positions on X-axis
522
+ for i in range(0, num_sites + 1, 1):
523
+ x = margin + (i / num_sites) * usable_width
524
+ _axes.append(
525
+ Line(x1=x, y1=svg_height - margin, x2= x, y2=svg_height - margin - 5, stroke="black")
526
+ )
527
+
528
+ # ===== HISTOGRAMS PER SITE =====
529
+ histogram_y = svg_height - 5
530
+ bar_width = 5
531
+ bar_spacing = 2 # Space between the 3 bars
532
+ bar_max_height = 40
533
+
534
+ _axes.append(
535
+ Text(
536
+ x=margin,
537
+ y=histogram_y - 40,
538
+ text="Cluster Distribution per Site (16 shrubs each)",
539
+ class_="axis-title"
540
+ )
541
+ )
542
+
543
+ # Colors for clusters
544
+ cluster_colors = {
545
+ '1': "#2d46dc",
546
+ '2': "#91d76e", # Green
547
+ '3': "#be2d32" # Red
548
+ }
549
+
550
+ # Draw histogram for each site in filtered_flowers
551
+ for site_id_ in filtered_flowers['Site ID'].values:
552
+ # Get ordinal position from filtered_for_plot
553
+ ord_pos_val = filtered_for_plot[filtered_for_plot['Site ID'] == site_id_]['ordinal_pos'].values[0]
554
+ site_x = margin + (ord_pos_val / num_sites) * usable_width
555
+
556
+ # Get cluster counts for this site
557
+ if site_id_ in cluster_counts.index:
558
+ counts = cluster_counts.loc[site_id_, ['1', '2', '3']]
559
+
560
+ # Draw 3 bars side-by-side
561
+ for cluster_idx, cluster in enumerate(['1', '2', '3']):
562
+ count = counts[cluster]
563
+ bar_height = (count / 16) * bar_max_height
564
+
565
+ # Calculate x position for each bar (3 bars side-by-side)
566
+ bar_x = site_x - (bar_width + bar_spacing) + cluster_idx * (bar_width + bar_spacing)
567
+
568
+ if bar_height > 0:
569
+ _axes.append(
570
+ Rect(
571
+ x=bar_x-2.5,
572
+ y=histogram_y - bar_height,
573
+ width=bar_width,
574
+ height=bar_height,
575
+ fill=cluster_colors[cluster]
576
+ )
577
+ )
578
+
579
+ # Y-axis: draw the line and label it
580
+ _axes.append(
581
+ Line(
582
+ x1=margin,
583
+ y1=top_margin + margin -15,
584
+ x2=margin,
585
+ y2=svg_height - margin,
586
+ stroke="black",
587
+ )
588
+ )
589
+
590
+ _axes.append(
591
+ Text(
592
+ x= margin,
593
+ y= top_margin + margin -23,
594
+ text="Mean coffee yield (kg/ha)",
595
+ class_="axis-title"
596
+ )
597
+ )
598
+
599
+ #Add manual arrow at top of y-axis
600
+ arrow_tip_x = margin
601
+ arrow_tip_y = top_margin + margin - 15
602
+ _axes.append(Line(x1=arrow_tip_x, y1=arrow_tip_y, x2=arrow_tip_x - 5, y2=arrow_tip_y + 10, stroke="black"))
603
+ _axes.append(Line(x1=arrow_tip_x, y1=arrow_tip_y, x2=arrow_tip_x + 5, y2=arrow_tip_y + 10, stroke="black"))
604
+
605
+ #Add positions on Y-axis
606
+ for val in [0, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000, 5500]:
607
+
608
+ y = top_margin + margin + (y_max - val) / (y_max - y_min) * usable_height
609
+
610
+ _axes.append(
611
+ Line(
612
+ x1=margin - 5,
613
+ y1=y,
614
+ x2=margin,
615
+ y2=y,
616
+ stroke="black"
617
+ )
618
+ )
619
+
620
+ _axes.append(
621
+ Text(
622
+ x=margin -50,
623
+ y=y + 5,
624
+ text=str(val),
625
+ class_="axis-label"
626
+ )
627
+ )
628
+
629
+ #Add dashed reference lines for Y-axis positions
630
+ # Make lines longer for 0 and 2000
631
+ if val in [500, 1000, 1500, 2000]:
632
+ x2_end = svg_width - 50 # Longer
633
+ else:
634
+ x2_end = usable_width + margin # Normal length
635
+
636
+ _axes.append(
637
+ Line(
638
+ x1=margin,
639
+ y1=y,
640
+ x2=x2_end,
641
+ y2=y,
642
+ stroke="lightgray",
643
+ stroke_dasharray="3,3",
644
+ opacity=0.7
645
+ )
646
+ )
647
+
648
+
649
+ # ===== TITLE ======
650
+ _axes.append(
651
+ Text(
652
+ x=svg_width / 2,
653
+ y= 50, # top_margin / 2 + 10,
654
+ text="Exploring Coffee Yield Patterns: Structure Index, Plant Abundance, and Plant Richness",
655
+ class_="main-title",
656
+ text_anchor="middle"
657
+ )
658
+ )
659
+ # Add subtitle
660
+ _axes.append(
661
+ Text(
662
+ x=svg_width / 2,
663
+ y= 75, #top_margin / 2 + 32,
664
+ text="Each flower represents a site; flower petals show abundance and richness of co-occuring plant species. Min-max lines indicate yield variation across 2017-2019.",
665
+ class_="subtitle",
666
+ text_anchor="middle"
667
+ )
668
+ )
669
+
670
+
671
+ # ===== LEGENDS =====
672
+
673
+ # ===== RIGHT SIDE =====
674
+
675
+ legend_x = usable_width + 120
676
+ legend_y = top_margin + margin
677
+
678
+ # ===== PART A: PLANT SPECIES LEGENDS =====
679
+
680
+ # ===== 1) PLANT SPECIES TYPE =====
681
+ _axes.append(
682
+ Text(
683
+ x=legend_x,
684
+ y=legend_y,
685
+ text="Plant Species Type",
686
+ class_="axis-title"
687
+ )
688
+ )
689
+
690
+ legend_colors = [
691
+ ("orange", "Herbaceous plant species"),
692
+ ("blue", "Bryophyte plant species"),
693
+ ("green", "Woody plant species"),
694
+ ]
695
+
696
+ for i, (color, label) in enumerate(legend_colors):
697
+ y_pos = legend_y + 20 + i * 18
698
+ _axes.append(
699
+ Ellipse(cx=legend_x, cy=y_pos, rx=5, ry=5, fill=color, opacity=0.6)
700
+ )
701
+ _axes.append(
702
+ Text(x=legend_x + 15, y=y_pos + 4, text=label, class_="axis-label")
703
+ )
704
+
705
+ # ===== 2) PETAL LENGTH = ABUNDANCE =====
706
+ legend_y_abundance = legend_y + 110
707
+
708
+ _axes.append(
709
+ Text(
710
+ x=legend_x,
711
+ y=legend_y_abundance,
712
+ text="Petal Length = Plant Abundance",
713
+ class_="axis-title"
714
+ )
715
+ )
716
+
717
+ _axes.append(
718
+ Text(
719
+ x=legend_x,
720
+ y=legend_y_abundance + 16,
721
+ text="(% of plant community)",
722
+ class_="axis-label",
723
+ font_size=8
724
+ )
725
+ )
726
+
727
+ # 5 petals showing abundance gradient with actual percentage values
728
+ abundance_values = [0, 25, 50, 75, 100]
729
+ petal_lengths = [2, 6, 10, 14, 18]
730
+ spacing = 50
731
+
732
+ for i, (abundance, petal_len) in enumerate(zip(abundance_values, petal_lengths)):
733
+ ex = legend_x + 5 + i * spacing
734
+ ey = legend_y_abundance + 40
735
+ _axes.append(
736
+ Ellipse(
737
+ cx=ex,
738
+ cy=ey,
739
+ rx=1.5,
740
+ ry=petal_len,
741
+ fill="gray",
742
+ opacity=0.3,
743
+ transform=f"rotate(90, {ex}, {ey})"
744
+ )
745
+ )
746
+
747
+ # Add value labels below
748
+ _axes.append(
749
+ Text(x=ex - 5, y=legend_y_abundance + 62, text=f"{abundance}%",
750
+ class_="axis-label", font_size=7)
751
+ )
752
+
753
+ # ===== 3) PETAL OPACITY = SPECIES RICHNESS =====
754
+ legend_y_richness = legend_y_abundance + 110
755
+
756
+ _axes.append(
757
+ Text(
758
+ x=legend_x,
759
+ y=legend_y_richness,
760
+ text="Petal Opacity = Species Richness",
761
+ class_="axis-title"
762
+ )
763
+ )
764
+
765
+ _axes.append(
766
+ Text(
767
+ x=legend_x,
768
+ y=legend_y_richness + 16,
769
+ text="(normalized 0.2-1.0 scale)",
770
+ class_="axis-label",
771
+ font_size=8
772
+ )
773
+ )
774
+
775
+ # 5 circles showing richness gradient with actual species counts
776
+ richness_values = [
777
+ (herb_richness_min, f"{int(herb_richness_min)} sp."),
778
+ ((herb_richness_min + herb_richness_max) * 0.25, f"{int((herb_richness_min + herb_richness_max) * 0.25)} sp."),
779
+ ((herb_richness_min + herb_richness_max) * 0.5, f"{int((herb_richness_min + herb_richness_max) * 0.5)} sp."),
780
+ ((herb_richness_min + herb_richness_max) * 0.75, f"{int((herb_richness_min + herb_richness_max) * 0.75)} sp."),
781
+ (herb_richness_max, f"{int(herb_richness_max)} sp."),
782
+ ]
783
+
784
+ opacities_richness = [0.2, 0.4, 0.6, 0.8, 1.0]
785
+
786
+ for i, (opacity, (richness_val, richness_label)) in enumerate(zip(opacities_richness, richness_values)):
787
+ ex = legend_x + 5 + i * spacing
788
+ ey = legend_y_richness + 40
789
+ _axes.append(
790
+ Ellipse(cx=ex, cy=ey, rx=5, ry=5, fill="gray", opacity=opacity)
791
+ )
792
+
793
+ # Add value labels below
794
+ _axes.append(
795
+ Text(x=ex - 8, y=legend_y_richness + 62, text=richness_label,
796
+ class_="axis-label", font_size=7)
797
+ )
798
+
799
+
800
+ # Frame around three Plant Species legends (Type, Abundance, Richness)
801
+ frame_padding = 12
802
+ _axes.append(
803
+ Rect(
804
+ x=legend_x - frame_padding,
805
+ y=legend_y - frame_padding,
806
+ width=320,
807
+ height=legend_y_richness + 100 - (legend_y - frame_padding),
808
+ fill="none",
809
+ stroke="#cccccc",
810
+ stroke_width=1.5,
811
+ opacity=0.9
812
+ )
813
+ )
814
+
815
+ # ===== STRUCTURE INDEX DENSITY LEGEND =====
816
+ density_legend_y = legend_y_richness + 145
817
+
818
+ #add title
819
+ _axes.append(
820
+ Text(
821
+ x=legend_x,
822
+ y=density_legend_y - 15,
823
+ text="Structure Index Density",
824
+ class_="axis-title"
825
+ )
826
+ )
827
+
828
+ # Create a vertical gradient scale showing gap size progression
829
+ gap_values = ["gap ≈ 0", "gap < 0.03", "gap < 0.06", "gap < 0.10", "gap ≥ 0.10"]
830
+ opacity_values = [0.35, 0.32, 0.25, 0.18, 0.10]
831
+
832
+ # Top label - High density
833
+ _axes.append(
834
+ Text(x=legend_x + 30, y=density_legend_y, text="High density (compressed)",
835
+ class_="axis-label", font_size=9)
836
+ )
837
+
838
+ # Draw rectangles vertically
839
+ for i, (gap, opacity) in enumerate(zip(gap_values, opacity_values)):
840
+ y_pos = density_legend_y + 10 + i * 22
841
+
842
+ _axes.append(
843
+ Rect(x=legend_x, y=y_pos, width=20, height=18, fill="gray", opacity=opacity)
844
+ )
845
+
846
+ _axes.append(
847
+ Text(x=legend_x + 28, y=y_pos + 13, text=gap,
848
+ class_="axis-label", font_size=9)
849
+ )
850
+
851
+ # Bottom label - Low density
852
+ _axes.append(
853
+ Text(x=legend_x + 30, y=density_legend_y + 10 + 5 * 22 + 15,
854
+ text="Low density (spread)", class_="axis-label", font_size=9)
855
+ )
856
+
857
+ # Frame around Structure Index Density legend
858
+ _axes.append(
859
+ Rect(
860
+ x=legend_x - frame_padding,
861
+ y= 430, #density_legend_y - frame_padding,
862
+ width=320,
863
+ height=5 * 22 + 60 +15,
864
+ fill="none",
865
+ stroke="#cccccc",
866
+ stroke_width=1.5,
867
+ opacity=0.9
868
+ )
869
+ )
870
+
871
+
872
+ # ===== CLUSTER LEGEND =====
873
+ cluster_legend_x = usable_width + 350
874
+ cluster_legend_y = histogram_y - 63
875
+
876
+ _axes.append(
877
+ Text(
878
+ x=cluster_legend_x -143,
879
+ y=cluster_legend_y +43,
880
+ text="Cluster Distribution",
881
+ class_="axis-title"
882
+ )
883
+ )
884
+
885
+ cluster_dataa = [
886
+ ("#2d46dc", "Cluster 1"),
887
+ ("#91d76e", "Cluster 2"),
888
+ ("#be2d32", "Cluster 3"),
889
+ ]
890
+
891
+ for i, (color, label) in enumerate(cluster_dataa):
892
+ y_pos = cluster_legend_y + 16 + i * 16
893
+ _axes.append(
894
+ Rect(x=cluster_legend_x, y=y_pos, width=10, height=10, fill=color)
895
+ )
896
+ _axes.append(
897
+ Text(x=cluster_legend_x + 18, y=y_pos + 10, text=label, class_="axis-label")
898
+ )
899
+
900
+
901
+
902
+ # ===== AGGREGATE FLOWERS (Bottom right area) =====
903
+
904
+ #create two groups
905
+ top_half = filtered_flowers.nlargest(len(filtered_flowers)//2, "Mean_CC_Yield")
906
+ bottom_half = filtered_flowers.nsmallest(len(filtered_flowers)//2, "Mean_CC_Yield")
907
+
908
+ # ABUNDANCE (for petal length)
909
+ g1_herb = bottom_half["Herb_abundance"].mean()
910
+ g1_bryo = bottom_half["Bryo_abundance"].mean()
911
+ g1_woody = bottom_half["Woody_abundance"].mean()
912
+
913
+ g2_herb = top_half["Herb_abundance"].mean()
914
+ g2_bryo = top_half["Bryo_abundance"].mean()
915
+ g2_woody = top_half["Woody_abundance"].mean()
916
+
917
+ # RICHNESS (for petal opacity)
918
+ g1_herb_richness = bottom_half["Veg_Spps"].mean()
919
+ g1_bryo_richness = bottom_half["Bryo_Spps"].mean()
920
+ g1_woody_richness = bottom_half["Woody_Spps"].mean()
921
+
922
+ g2_herb_richness = top_half["Veg_Spps"].mean()
923
+ g2_bryo_richness = top_half["Bryo_Spps"].mean()
924
+ g2_woody_richness = top_half["Woody_Spps"].mean()
925
+
926
+ #y positions fixed to mean yield of each group
927
+ flower_x = usable_width + 200
928
+ flower_y1 = top_margin + margin + (y_max - bottom_half["Mean_CC_Yield"].mean()) / (y_max - y_min) * usable_height #+800
929
+ flower_y2 = top_margin + margin + (y_max - top_half["Mean_CC_Yield"].mean()) / (y_max - y_min) * usable_height # + 900
930
+
931
+ #define draw_flower mentioning position, direction, abundance for two groups, colour etc
932
+ def draw_flower(cx, cy, herb, bryo, woody, herb_rich, bryo_rich, woody_rich, scale=1):
933
+ petals = [
934
+ (90, herb, "orange", herb_rich, herb_richness_min, herb_richness_max),
935
+ (210, bryo, "blue", bryo_rich, bryo_richness_min, bryo_richness_max),
936
+ (330, woody, "green", woody_rich, woody_richness_min, woody_richness_max),
937
+ ]
938
+ flower_elements = []
939
+ for angle, abundance, color, richness, min_richness, max_richness in petals:
940
+ rad = math.radians(angle)
941
+ petal_length = abundance / 100 * 14 * scale
942
+ opacity = get_opacity_from_richness(richness, min_richness, max_richness)
943
+ ex = cx + math.sin(rad) * petal_length
944
+ ey = cy - math.cos(rad) * petal_length
945
+ flower_elements.append(
946
+ Ellipse(
947
+ cx=ex,
948
+ cy=ey,
949
+ rx=3 * scale,
950
+ ry=petal_length,
951
+ fill=color,
952
+ opacity=opacity,
953
+ transform=f"rotate({angle}, {ex}, {ey})"
954
+ )
955
+ )
956
+ return flower_elements
957
+
958
+ # draw both aggregate flowers using definition
959
+ _elements += draw_flower(flower_x, flower_y1, g1_herb, g1_bryo, g1_woody, g1_herb_richness, g1_bryo_richness, g1_woody_richness, scale=3)
960
+ _elements += draw_flower(flower_x, flower_y2, g2_herb, g2_bryo, g2_woody, g2_herb_richness, g2_bryo_richness, g2_woody_richness, scale=3)
961
+
962
+ #add labels
963
+ _axes.append(
964
+ Text(
965
+ x=legend_x#flower_x-60
966
+ , y=density_legend_y +235,
967
+ text="Aggregate flowers of two groups comparing low/high yield",
968
+ class_="axis-title"#,
969
+ #font_size=6
970
+ )
971
+ )
972
+ _axes.append(Text(
973
+ x=legend_x #flower_x-60
974
+ , y=flower_y1 - 60,
975
+ text="Sites with low yield (Lower half of 60 sites/Bottom 10)", class_="axis-label"#, font_size=7
976
+ ))
977
+ _axes.append(Text(
978
+ x=legend_x,
979
+ #flower_x-60,
980
+ y=flower_y2 -60,
981
+ text="Sites with top yield (Upper half of 60 sites/Top 10)", class_="axis-label"#, font_size=7
982
+ ))
983
+
984
+ # ===== DENSITY VISUALISATION BACKGROUND =====
985
+ #add values of structure index in a list to calculate gaps
986
+ struct_values = structureindex.values
987
+
988
+ for idx in range(len(struct_values) - 1):
989
+ gap = struct_values[idx + 1] - struct_values[idx]
990
+
991
+ #size of gap determines opacity
992
+ if gap == 0.0000:
993
+ opacity = 0.35
994
+ elif gap < 0.03:
995
+ opacity = 0.32
996
+ elif gap < 0.06:
997
+ opacity = 0.25
998
+ elif gap < 0.10:
999
+ opacity = 0.18
1000
+ else:
1001
+ opacity = 0.10
1002
+
1003
+ #define positions for drawing rectangle (in between sites)
1004
+ x_curr = margin + (ordinal_pos[idx] / num_sites) * usable_width
1005
+ x_next = margin + (ordinal_pos[idx + 1] / num_sites) * usable_width
1006
+
1007
+ #draw rectangles between each site/structure index value, that span across the whole y-axis, using opacity variable to change according to gap size
1008
+ _axes.append(
1009
+ Rect(x=x_curr, y=margin+ top_margin, width=x_next - x_curr,
1010
+ height=usable_height, fill="gray", opacity=opacity)
1011
+ )
1012
+
1013
+ # ===== CREATING SVG FRAME =====
1014
+ _svg = SVG(width=svg_width, height=svg_height, class_="abc",
1015
+ elements=_elements+_axes)
1016
+ svg_str = _svg.as_str()
1017
+
1018
+ mo.vstack([
1019
+ mo.Html(svg_str),
1020
+ mo.hstack([
1021
+ filter_selector,
1022
+ flower_size
1023
+ ])
1024
+ ])
1025
+ return (
1026
+ abundance,
1027
+ abundance_values,
1028
+ angle,
1029
+ arrow_tip_x,
1030
+ arrow_tip_y,
1031
+ bar_height,
1032
+ bar_max_height,
1033
+ bar_spacing,
1034
+ bar_width,
1035
+ bar_x,
1036
+ bottom_half,
1037
+ bryo_,
1038
+ bryo_richness,
1039
+ cluster,
1040
+ cluster_colors,
1041
+ cluster_dataa,
1042
+ cluster_idx,
1043
+ cluster_legend_x,
1044
+ cluster_legend_y,
1045
+ color,
1046
+ count,
1047
+ counts,
1048
+ cx,
1049
+ cy,
1050
+ cy_max,
1051
+ cy_min,
1052
+ density_legend_y,
1053
+ draw_flower,
1054
+ ex,
1055
+ ey,
1056
+ flower_x,
1057
+ flower_y1,
1058
+ flower_y2,
1059
+ frame_padding,
1060
+ g1_bryo,
1061
+ g1_bryo_richness,
1062
+ g1_herb,
1063
+ g1_herb_richness,
1064
+ g1_woody,
1065
+ g1_woody_richness,
1066
+ g2_bryo,
1067
+ g2_bryo_richness,
1068
+ g2_herb,
1069
+ g2_herb_richness,
1070
+ g2_woody,
1071
+ g2_woody_richness,
1072
+ gap,
1073
+ gap_values,
1074
+ herb_,
1075
+ herb_richness,
1076
+ histogram_y,
1077
+ i,
1078
+ idx,
1079
+ label,
1080
+ legend_colors,
1081
+ legend_x,
1082
+ legend_y,
1083
+ legend_y_abundance,
1084
+ legend_y_richness,
1085
+ margin,
1086
+ max_richness,
1087
+ max_y,
1088
+ min_richness,
1089
+ min_y,
1090
+ num_sites,
1091
+ opacities_richness,
1092
+ opacity,
1093
+ opacity_values,
1094
+ ord_pos,
1095
+ ord_pos_val,
1096
+ petal_len,
1097
+ petal_length,
1098
+ petal_lengths,
1099
+ petals,
1100
+ rad,
1101
+ richness,
1102
+ richness_label,
1103
+ richness_val,
1104
+ richness_values,
1105
+ site_,
1106
+ site_id_,
1107
+ site_x,
1108
+ spacing,
1109
+ struct_values,
1110
+ structure_,
1111
+ svg_str,
1112
+ top_half,
1113
+ top_margin,
1114
+ usable_height,
1115
+ usable_width,
1116
+ val,
1117
+ woody_,
1118
+ woody_richness,
1119
+ x,
1120
+ x2_end,
1121
+ x_curr,
1122
+ x_max,
1123
+ x_min,
1124
+ x_next,
1125
+ y,
1126
+ y_max,
1127
+ y_min,
1128
+ y_pos,
1129
+ yield_,
1130
+ )
1131
+
1132
+
1133
+ if __name__ == "__main__":
1134
+ app.run()