Spaces:
Sleeping
Sleeping
Download visual1.py from meleysse/marimo-app-template-test: direct link, hf CLI and curl.
- Browser
- Download file 37.9 kB
-
https://huggingface.co/spaces/meleysse/marimo-app-template-test/resolve/main/visual1.py
- Command line
-
hf download hf://spaces/meleysse/marimo-app-template-test/visual1.py
-
curl -L -o visual1.py https://huggingface.co/spaces/meleysse/marimo-app-template-test/resolve/main/visual1.py
37.9 kB
import marimo
__generated_with = "0.11.26"
app = marimo.App(width="medium")
@app.cell
def _():
import marimo as mo
import pandas as pd
import math
from svg import SVG, Circle, Text, G, Line, Ellipse, Rect, Title
import numpy as np
return Circle, Ellipse, G, Line, Rect, SVG, Text, Title, math, mo, np, pd
@app.cell
def _(pd):
# ===== IMPORT DATASETS =====
coffeeyield = pd.read_excel("Coffee_yield.xlsx")
coffeestructureindex_management = pd.read_excel("Environmental_and_management_variables.xlsx")
plant_species_richness = pd.read_excel("Plant_species_richness.xlsx")
return coffeestructureindex_management, coffeeyield, plant_species_richness
@app.cell
def _(pd):
# ===== PREPARE WOODY DATA =====
#Load the excelfile
woody_species_abundance = pd.read_excel("Woody_species_abundance.xlsx")
woody_species_abundance
#Creating dataframe of total abundance of woody species, per Site ID
woody_totals = woody_species_abundance.iloc[:, 1:].sum().reset_index()
#Rename the columns to meaningful names
woody_totals.columns = ["Site ID", "Woody_total"]
#Normalise the abundance values to 0-100 scale for comparability
#Divide each value by max (0-1 scale) and multiply by 100 (0-100 scale)
woody_totals["Woody_abundance"] = (woody_totals["Woody_total"] / woody_totals["Woody_total"].max()) * 100
#Keep only the Site ID and normalised abundance columns
w_abundance = woody_totals[["Site ID", "Woody_abundance"]]
#w_abundance
return w_abundance, woody_species_abundance, woody_totals
@app.cell
def _(pd):
# ===== PREPARE BRYOPHYTE DATA =====
#Load the txtfile
bryophyte_species_abundance = pd.read_csv("Bryophyte_frequency.txt", sep="\t")
#Creating dataframe of total abundance of bryo species, per Site ID
bryo_totals = bryophyte_species_abundance.iloc[:, 1:].sum().reset_index()
#Rename the columns to meaningful names
bryo_totals.columns = ["Site ID", "Bryo_total"]
#Normalise the abundance values to 0-100 scale for comparability
#Divide each value by max (0-1 scale) and multiply by 100 (0-100 scale)
bryo_totals["Bryo_abundance"] = (bryo_totals["Bryo_total"] / bryo_totals["Bryo_total"].max()) * 100
#Keep only the Site ID and normalised abundance columns
b_abundance = bryo_totals[["Site ID", "Bryo_abundance"]]
#b_abundance
return b_abundance, bryo_totals, bryophyte_species_abundance
@app.cell(hide_code=True)
def _():
# # ===== VERIFY BRYOPHYTE DATA =====
# # See the raw totals BEFORE normalization
# print("Raw bryophyte totals (before normalization):")
# print(bryo_totals[["Site ID", "Bryo_total"]])
# # See which site has the max
# print(f"\nMax bryo total: {bryo_totals['Bryo_total'].max()}")
# # Check a specific site (e.g., Ge1)
# ge1_row = bryo_totals[bryo_totals["Site ID"] == "Ge1"]
# if not ge1_row.empty:
# ge1_raw = ge1_row["Bryo_total"].values[0]
# print(f"Ge1 raw total: {ge1_raw}")
# # Verify the normalization calculation manually
# ge1_normalized_manual = (ge1_raw / bryo_totals["Bryo_total"].max()) * 100
# ge1_normalized_actual = ge1_row["Bryo_abundance"].values[0]
# print(f"Ge1 normalized (manual calc): {ge1_normalized_manual:.2f}")
# print(f"Ge1 normalized (from data): {ge1_normalized_actual:.2f}")
# print(f"Match: {abs(ge1_normalized_manual - ge1_normalized_actual) < 0.01}")
# else:
# print("Ge1 not found in data")
# # Show distribution
# print(f"\nBryo abundance range: {bryo_totals['Bryo_abundance'].min():.2f} to {bryo_totals['Bryo_abundance'].max():.2f}")
# # Display final result
# print("\nFinal bryophyte abundance (0-100 scale):")
# print(b_abundance.head(10))
return
@app.cell
def _(pd):
# ===== PREPARE HERB DATA =====
#Load the txtfile
herb_species_abundance = pd.read_csv("Herbaceous_vegetation_Abundance.txt", sep="\t")
#Set Site ID as index and then sum species columns for total abundance
herb_totals = herb_species_abundance.set_index(herb_species_abundance.columns[0]).iloc[:, :].sum(axis=1).reset_index()
#Rename the columns to meaningful names
herb_totals.columns = ["Site ID", "Herb_total"]
#Normalise the abundance values to 0-100 scale for comparability
#Divide each value by max (0-1 scale) and multiply by 100 (0-100 scale)
herb_totals["Herb_abundance"] = (herb_totals["Herb_total"] / herb_totals["Herb_total"].max()) * 100
herb_totals
#Keep only the Site ID and normalised abundance columns
h_abundance = herb_totals[["Site ID", "Herb_abundance"]]
#h_abundance
return h_abundance, herb_species_abundance, herb_totals
@app.cell
def _(
b_abundance,
coffeestructureindex_management,
coffeeyield,
h_abundance,
plant_species_richness,
w_abundance,
):
merged = coffeeyield \
.merge(coffeestructureindex_management, on="Site ID") \
.merge(plant_species_richness, on="Site ID") \
.merge(w_abundance, on="Site ID")\
.merge(b_abundance, on="Site ID")\
.merge(h_abundance, on="Site ID")
merged
return (merged,)
@app.cell
def _(filtered_flowers, filtered_for_plot, pd):
# # ===== PREPARE CLUSTER DATA FOR HISTOGRAMS =====
# # Load cluster distribution data
# Coffee_structure_index_variables = pd.read_excel("Coffee_structure_index_variables.xlsx")
# cluster_data = Coffee_structure_index_variables.copy()
# cluster_data
# # Group by Site ID and count clusters
# cluster_counts = cluster_data.groupby(['Site ID', 'Fitted cluster']).size().unstack(fill_value=0)
# # Ensure all clusters exist (1, 2, 3)
# for cluster in [1, 2, 3]:
# if cluster not in cluster_counts.columns:
# cluster_counts[cluster] = 0
# # Get only sites in filtered_flowers
# cluster_counts = cluster_counts.loc[cluster_counts.index.isin(filtered_flowers['Site ID'])]
# # Sort by ordinal_pos to match graph order
# cluster_counts = cluster_counts.join(
# filtered_for_plot[['Site ID', 'ordinal_pos']].set_index('Site ID'),
# how='left'
# )
# cluster_counts = cluster_counts.sort_values('ordinal_pos')
# cluster_counts
# ===== PREPARE CLUSTER DATA FOR HISTOGRAMS =====
cluster_data = pd.read_excel("Coffee_structure_index_variables.xlsx")
# Simple: group by Site ID and cluster, count rows
cluster_counts = cluster_data.groupby(['Site ID', 'Fitted cluster']).size().unstack(fill_value=0)
# Make sure we have columns 1, 2, 3 (add if missing)
for col in [1, 2, 3]:
if col not in cluster_counts.columns:
cluster_counts[col] = 0
# Keep only sites we're showing
cluster_counts = cluster_counts[cluster_counts.index.isin(filtered_flowers['Site ID'])]
# Sort to match graph order
site_order = filtered_for_plot[filtered_for_plot['Site ID'].isin(cluster_counts.index)].set_index('Site ID')
cluster_counts = cluster_counts.loc[site_order.index]
# FIX: Rename integer columns to strings
cluster_counts.columns = cluster_counts.columns.astype(str)
cluster_counts
return cluster_counts, cluster_data, col, site_order
@app.cell
def _(filter_selector, merged, pd):
# ===== PREPARE DATA FOR VISUALISATION. =====
# ===== CREATING TWO VARIABLES FOR SELECTOR: one for plotting whole graph, one for filtering flowers only =====
#Determine which sites to display (all variables for axis/background)
filtered_for_plot = merged.copy()
filtered_for_plot = filtered_for_plot.sort_values("Coffee structure index").reset_index(drop=True)
filtered_for_plot["ordinal_pos"] = range(1, len(filtered_for_plot) + 1)
# Define min/max yield for ALL sites (needed for axes)
filtered_for_plot["min_yield"] = filtered_for_plot[["CC_Yield_2017", "CC_Yield_2018", "CC_Yield_2019"]].min(axis=1, skipna=True)
filtered_for_plot["max_yield"] = filtered_for_plot[["CC_Yield_2017", "CC_Yield_2018", "CC_Yield_2019"]].max(axis=1, skipna=True)
#Determine which flowers are shown (changes based on filter)
if filter_selector.value == "All sites":
filtered_flowers = filtered_for_plot.copy()
show_labels = False
else: # "Top 10 + Bottom 10 yield"
t10 = merged.nlargest(10, "Mean_CC_Yield")
b10 = merged.nsmallest(10, "Mean_CC_Yield")
filtered_flowers = pd.concat([t10, b10]).sort_values("Coffee structure index").reset_index(drop=True)
show_labels = True
# Add ordinal_pos, min_yield, max_yield from filtered_for_plot + add if to avoid duplicates (every time code runs)
if "ordinal_pos" not in filtered_flowers.columns:
filtered_flowers = filtered_flowers.merge(
filtered_for_plot[["Site ID", "ordinal_pos", "min_yield", "max_yield"]],
on="Site ID",
how="left"
)
# ===== PREPERATION OF RICHNESS VARIABLE: CALCULATE MIN/MAX RICHNESS FOR NORMALIZATION =====
herb_richness_min = filtered_flowers["Veg_Spps"].min()
herb_richness_max = filtered_flowers["Veg_Spps"].max()
bryo_richness_min = filtered_flowers["Bryo_Spps"].min()
bryo_richness_max = filtered_flowers["Bryo_Spps"].max()
woody_richness_min = filtered_flowers["Woody_Spps"].min()
woody_richness_max = filtered_flowers["Woody_Spps"].max()
# Function to normalize richness and convert to opacity in petals
def get_opacity_from_richness(value, min_val, max_val):
if max_val == min_val: # Handle case where all values are the same
normalized = 0.5
else:
normalized = (value - min_val) / (max_val - min_val)
return 0.2 + (normalized * 0.8) # Maps to 0.2-1.0 opacity range
# ===== EXTRACT VARIABLES for plotting ======
structureindex = filtered_for_plot["Coffee structure index"]
mean_coffee_yield = filtered_for_plot["Mean_CC_Yield"]
site_id = filtered_for_plot["Site ID"]
herb_abundance = filtered_for_plot["Herb_abundance"]
bryo_abundance = filtered_for_plot["Bryo_abundance"]
woody_abundance = filtered_for_plot["Woody_abundance"]
ordinal_pos = filtered_for_plot["ordinal_pos"]
#Extract variables for flowers (filtered)
flower_sites = filtered_flowers["Site ID"].tolist()
print(f"All sites to display: {len(filtered_for_plot)}")
print(f"Flowers to show: {len(filtered_flowers)}")
return (
b10,
bryo_abundance,
bryo_richness_max,
bryo_richness_min,
filtered_flowers,
filtered_for_plot,
flower_sites,
get_opacity_from_richness,
herb_abundance,
herb_richness_max,
herb_richness_min,
mean_coffee_yield,
ordinal_pos,
show_labels,
site_id,
structureindex,
t10,
woody_abundance,
woody_richness_max,
woody_richness_min,
)
@app.cell
def _():
# filtered_for_plot
# filtered_flowers
return
@app.cell
def _():
#svg frame
svg_width=2350
svg_height=1300
return svg_height, svg_width
@app.cell
def _(mo):
mo.md(
"""
<!-- CSS for layout of svg-->
<style>
svg.abc {
border: 1px solid;
background: #fafafa;
border-radius: 4px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}
.axis-label {
font-size: 11px;
fill: #333;
}
.axis-title {
font-size: 13px;
fill: #222;
font-weight: 500;
}
.main-title {
font-size: 20px;
fill: black;
font-weight: 600;
}
.subtitle {
font-size: 11px;
fill: #6b7280;
font-weight: 400;
}
circle.nq1 {
fill: #2563eb;
stroke: #1e40af;
stroke-width: 0.5px;
opacity: 0.6;
}
ellipse {
stroke: none;
}
line {
stroke-linecap: round;
stroke-linejoin: round;
}
</style>
"""
)
return
@app.cell
def _(mo):
flower_size = mo.ui.slider(start=1, stop=2, step=0.25, value=1, label="Flower size")
flower_size
return (flower_size,)
@app.cell
def _(mo):
filter_selector = mo.ui.dropdown(
options=["All sites", "Top 10 yield & Bottom 10 yield"],
label="Show sites"
)
filter_selector
return (filter_selector,)
@app.cell
def _(frame_padding, legend_y, legend_y_richness):
print(legend_y_richness + 100 - (legend_y - frame_padding))
print(legend_y - frame_padding)
return
@app.cell
def _(
Circle,
Ellipse,
Line,
Rect,
SVG,
Text,
bryo_richness_max,
bryo_richness_min,
cluster_counts,
filter_selector,
filtered_flowers,
filtered_for_plot,
flower_size,
get_opacity_from_richness,
herb_richness_max,
herb_richness_min,
math,
mo,
ordinal_pos,
structureindex,
svg_height,
svg_width,
woody_richness_max,
woody_richness_min,
):
#creating variable 'elements'
_elements = []
#Scaling of x-axis and y-axis
margin = 90
top_margin = 20 #add extra space at top for title
usable_width = svg_width - 6 * margin + 30
usable_height = svg_height - 2 * margin -top_margin
x_min = 1
x_max = 3
y_min = 0
y_max = 5500
num_sites = len(filtered_for_plot)
#===== LOOP FOR DRAWING ELEMENTS =====
#adding elements to svg - loop for circles, flower petals and dashed lines of min-max yield
#but instead of looping through all sites, we will loop through filtered_flowers (for selection 60 vs 20 site ids)
for structure_, yield_, site_, herb_, bryo_, woody_, herb_richness, bryo_richness, woody_richness, min_y, max_y, ord_pos in zip(
filtered_flowers["Coffee structure index"],
filtered_flowers["Mean_CC_Yield"],
filtered_flowers["Site ID"],
filtered_flowers["Herb_abundance"],
filtered_flowers["Bryo_abundance"],
filtered_flowers["Woody_abundance"],
filtered_flowers["Veg_Spps"], # Herb richness
filtered_flowers["Bryo_Spps"], # Bryo richness
filtered_flowers["Woody_Spps"], # Woody richness
filtered_flowers["min_yield"],
filtered_flowers["max_yield"],
#we need to get ordinal_pos from filtered_for_plot, not filtered_flowers
filtered_flowers["Site ID"].map(filtered_for_plot.set_index("Site ID")["ordinal_pos"])
):
#create position for site ids to draw circles, flowers etc.
cx = margin + (ord_pos/num_sites)*usable_width
cy = top_margin + margin + (y_max - yield_) / (y_max - y_min) * usable_height
cy_min = top_margin + margin + (y_max - min_y) / (y_max - y_min) * usable_height
cy_max = top_margin + margin + (y_max - max_y) / (y_max - y_min) * usable_height
#draw site ID name
_elements.append(
Text(x=cx, y= cy-10,
text=str(site_),
class_="axis-label", font_size=8)
)
#draw number of structure index per site ID at x-axis
_elements.append(
Text(x=cx-10-10, y=svg_height - margin +25,
text=f"{structure_:.2f}",
class_="axis-label", font_size=8,
transform=f"rotate(-45, {cx-10}, {svg_height - margin +15})")
)
#draw circles per site ID
_elements.append(
Circle(
cx=cx,
cy=cy,
r=3,
class_="nq1"
)
)
#DRAW MIN-MAX YIELD for three years - draw dashed line from min to max yield
_elements.append(
Line(
x1=cx, y1=cy_min,
x2=cx, y2=cy_max,
stroke="gray",
stroke_dasharray="3,3"
)
)
# - draw small square at max yield
_elements.append(
Rect(x=cx-3, y=cy_max-3, width=6, height=6, fill="gray")
)
# - draw small square at min yield
_elements.append(
Rect(x=cx-3, y=cy_min-3, width=6, height=6, fill="gray")
)
# each petal shows LENGTH = abundance, OPACITY = richness
#create three petals categories
petals = [
(90, herb_, "orange", herb_richness, herb_richness_min, herb_richness_max),
(210, bryo_, "blue", bryo_richness, bryo_richness_min, bryo_richness_max),
(330, woody_, "green", woody_richness, woody_richness_min, woody_richness_max),
]
#draw ellipses based on petals data: correct direction, length corresponding abundance, opacity corresponding richness, and colour per group
for angle, abundance, color, richness, min_richness, max_richness in petals:
rad = math.radians(angle)
petal_length = abundance / 100 * 16 * flower_size.value # scale to fit in the plot, ABUNDANCE
opacity = get_opacity_from_richness(richness, min_richness, max_richness) # OPACITY = richness
ex = cx + math.sin(rad) * petal_length
ey = cy - math.cos(rad) * petal_length
_elements.append(
Ellipse(
cx=ex,
cy=ey,
rx=3*flower_size.value,
ry=petal_length,
fill=color,
opacity=opacity,
transform=f"rotate({angle}, {ex}, {ey})"
)
)
# ===== AXES ======
#creating variable 'axes'
_axes = []
# X-axis: draw the line of the x-axis and label it
_axes.append(
Line(
x1=margin,
y1=svg_height - margin,
x2=usable_width + margin,
y2=svg_height - margin,
stroke="black"
)
)
_axes.append(
Text(
x= usable_width + 100,
y=svg_height - margin + 22,
text="Sites ordered by structure index (1-3)",
class_="axis-title"
)
)
#Add ordinal positions on X-axis
for i in range(0, num_sites + 1, 1):
x = margin + (i / num_sites) * usable_width
_axes.append(
Line(x1=x, y1=svg_height - margin, x2= x, y2=svg_height - margin - 5, stroke="black")
)
# ===== HISTOGRAMS PER SITE =====
histogram_y = svg_height - 5
bar_width = 5
bar_spacing = 2 # Space between the 3 bars
bar_max_height = 40
_axes.append(
Text(
x=margin,
y=histogram_y - 40,
text="Cluster Distribution per Site (16 shrubs each)",
class_="axis-title"
)
)
# Colors for clusters
cluster_colors = {
'1': "#2d46dc", # Purple
'2': "#91d76e", # Green
'3': "#be2d32" # Red
}
# Draw histogram for each site in filtered_flowers
for site_id_ in filtered_flowers['Site ID'].values:
# Get ordinal position from filtered_for_plot
ord_pos_val = filtered_for_plot[filtered_for_plot['Site ID'] == site_id_]['ordinal_pos'].values[0]
site_x = margin + (ord_pos_val / num_sites) * usable_width
# Get cluster counts for this site
if site_id_ in cluster_counts.index:
counts = cluster_counts.loc[site_id_, ['1', '2', '3']]
# Draw 3 bars side-by-side
for cluster_idx, cluster in enumerate(['1', '2', '3']):
count = counts[cluster]
bar_height = (count / 16) * bar_max_height
# Calculate x position for each bar (3 bars side-by-side)
bar_x = site_x - (bar_width + bar_spacing) + cluster_idx * (bar_width + bar_spacing)
if bar_height > 0:
_axes.append(
Rect(
x=bar_x-2.5,
y=histogram_y - bar_height,
width=bar_width,
height=bar_height,
fill=cluster_colors[cluster]
)
)
# Y-axis: draw the line and label it
_axes.append(
Line(
x1=margin,
y1=top_margin + margin -15,
x2=margin,
y2=svg_height - margin,
stroke="black",
)
)
_axes.append(
Text(
x= margin,
y= top_margin + margin -23,
text="Mean coffee yield (kg/ha)",
class_="axis-title"
)
)
#Add manual arrow at top of y-axis
arrow_tip_x = margin
arrow_tip_y = top_margin + margin - 15
_axes.append(Line(x1=arrow_tip_x, y1=arrow_tip_y, x2=arrow_tip_x - 5, y2=arrow_tip_y + 10, stroke="black"))
_axes.append(Line(x1=arrow_tip_x, y1=arrow_tip_y, x2=arrow_tip_x + 5, y2=arrow_tip_y + 10, stroke="black"))
#Add positions on Y-axis
for val in [0, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000, 5500]:
y = top_margin + margin + (y_max - val) / (y_max - y_min) * usable_height
_axes.append(
Line(
x1=margin - 5,
y1=y,
x2=margin,
y2=y,
stroke="black"
)
)
_axes.append(
Text(
x=margin -50,
y=y + 5,
text=str(val),
class_="axis-label"
)
)
#Add dashed reference lines for Y-axis positions
# Make lines longer for 0 and 2000
if val in [500, 1000, 1500, 2000]:
x2_end = svg_width - 50 # Longer
else:
x2_end = usable_width + margin # Normal length
_axes.append(
Line(
x1=margin,
y1=y,
x2=x2_end,
y2=y,
stroke="lightgray",
stroke_dasharray="3,3",
opacity=0.7
)
)
# ===== TITLE ======
_axes.append(
Text(
x=svg_width / 2,
y= 50, # top_margin / 2 + 10,
text="Exploring Coffee Yield Patterns: Structure Index, Plant Abundance, and Plant Richness",
class_="main-title",
text_anchor="middle"
)
)
# Add subtitle
_axes.append(
Text(
x=svg_width / 2,
y= 75, #top_margin / 2 + 32,
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.",
class_="subtitle",
text_anchor="middle"
)
)
# ===== LEGENDS =====
# ===== RIGHT SIDE =====
legend_x = usable_width + 120
legend_y = top_margin + margin
# ===== PART A: PLANT SPECIES LEGENDS =====
# ===== 1) PLANT SPECIES TYPE =====
_axes.append(
Text(
x=legend_x,
y=legend_y,
text="Plant Species Type",
class_="axis-title"
)
)
legend_colors = [
("orange", "Herbaceous plant species"),
("blue", "Bryophyte plant species"),
("green", "Woody plant species"),
]
for i, (color, label) in enumerate(legend_colors):
y_pos = legend_y + 20 + i * 18
_axes.append(
Ellipse(cx=legend_x, cy=y_pos, rx=5, ry=5, fill=color, opacity=0.6)
)
_axes.append(
Text(x=legend_x + 15, y=y_pos + 4, text=label, class_="axis-label")
)
# ===== 2) PETAL LENGTH = ABUNDANCE =====
legend_y_abundance = legend_y + 110
_axes.append(
Text(
x=legend_x,
y=legend_y_abundance,
text="Petal Length = Plant Abundance",
class_="axis-title"
)
)
_axes.append(
Text(
x=legend_x,
y=legend_y_abundance + 16,
text="(% of plant community)",
class_="axis-label",
font_size=8
)
)
# 5 petals showing abundance gradient with actual percentage values
abundance_values = [0, 25, 50, 75, 100]
petal_lengths = [2, 6, 10, 14, 18]
spacing = 50
for i, (abundance, petal_len) in enumerate(zip(abundance_values, petal_lengths)):
ex = legend_x + 5 + i * spacing
ey = legend_y_abundance + 40
_axes.append(
Ellipse(
cx=ex,
cy=ey,
rx=1.5,
ry=petal_len,
fill="gray",
opacity=0.3,
transform=f"rotate(90, {ex}, {ey})"
)
)
# Add value labels below
_axes.append(
Text(x=ex - 5, y=legend_y_abundance + 62, text=f"{abundance}%",
class_="axis-label", font_size=7)
)
# ===== 3) PETAL OPACITY = SPECIES RICHNESS =====
legend_y_richness = legend_y_abundance + 110
_axes.append(
Text(
x=legend_x,
y=legend_y_richness,
text="Petal Opacity = Species Richness",
class_="axis-title"
)
)
_axes.append(
Text(
x=legend_x,
y=legend_y_richness + 16,
text="(normalized 0.2-1.0 scale)",
class_="axis-label",
font_size=8
)
)
# 5 circles showing richness gradient with actual species counts
richness_values = [
(herb_richness_min, f"{int(herb_richness_min)} sp."),
((herb_richness_min + herb_richness_max) * 0.25, f"{int((herb_richness_min + herb_richness_max) * 0.25)} sp."),
((herb_richness_min + herb_richness_max) * 0.5, f"{int((herb_richness_min + herb_richness_max) * 0.5)} sp."),
((herb_richness_min + herb_richness_max) * 0.75, f"{int((herb_richness_min + herb_richness_max) * 0.75)} sp."),
(herb_richness_max, f"{int(herb_richness_max)} sp."),
]
opacities_richness = [0.2, 0.4, 0.6, 0.8, 1.0]
for i, (opacity, (richness_val, richness_label)) in enumerate(zip(opacities_richness, richness_values)):
ex = legend_x + 5 + i * spacing
ey = legend_y_richness + 40
_axes.append(
Ellipse(cx=ex, cy=ey, rx=5, ry=5, fill="gray", opacity=opacity)
)
# Add value labels below
_axes.append(
Text(x=ex - 8, y=legend_y_richness + 62, text=richness_label,
class_="axis-label", font_size=7)
)
# Frame around three Plant Species legends (Type, Abundance, Richness)
frame_padding = 12
_axes.append(
Rect(
x=legend_x - frame_padding,
y=legend_y - frame_padding,
width=320,
height=legend_y_richness + 100 - (legend_y - frame_padding),
fill="none",
stroke="#cccccc",
stroke_width=1.5,
opacity=0.9
)
)
# ===== STRUCTURE INDEX DENSITY LEGEND =====
density_legend_y = legend_y_richness + 145
#add title
_axes.append(
Text(
x=legend_x,
y=density_legend_y - 15,
text="Structure Index Density",
class_="axis-title"
)
)
# Create a vertical gradient scale showing gap size progression
gap_values = ["gap ≈ 0", "gap < 0.03", "gap < 0.06", "gap < 0.10", "gap ≥ 0.10"]
opacity_values = [0.35, 0.32, 0.25, 0.18, 0.10]
# Top label - High density
_axes.append(
Text(x=legend_x + 30, y=density_legend_y, text="High density (compressed)",
class_="axis-label", font_size=9)
)
# Draw rectangles vertically
for i, (gap, opacity) in enumerate(zip(gap_values, opacity_values)):
y_pos = density_legend_y + 10 + i * 22
_axes.append(
Rect(x=legend_x, y=y_pos, width=20, height=18, fill="gray", opacity=opacity)
)
_axes.append(
Text(x=legend_x + 28, y=y_pos + 13, text=gap,
class_="axis-label", font_size=9)
)
# Bottom label - Low density
_axes.append(
Text(x=legend_x + 30, y=density_legend_y + 10 + 5 * 22 + 15,
text="Low density (spread)", class_="axis-label", font_size=9)
)
# Frame around Structure Index Density legend
_axes.append(
Rect(
x=legend_x - frame_padding,
y= 430, #density_legend_y - frame_padding,
width=320,
height=5 * 22 + 60 +15,
fill="none",
stroke="#cccccc",
stroke_width=1.5,
opacity=0.9
)
)
# ===== CLUSTER LEGEND =====
cluster_legend_x = usable_width + 350
cluster_legend_y = histogram_y - 63
_axes.append(
Text(
x=cluster_legend_x -143,
y=cluster_legend_y +43,
text="Cluster Distribution",
class_="axis-title"
)
)
cluster_dataa = [
("#2d46dc", "Cluster 1"),
("#91d76e", "Cluster 2"),
("#be2d32", "Cluster 3"),
]
for i, (color, label) in enumerate(cluster_dataa):
y_pos = cluster_legend_y + 16 + i * 16
_axes.append(
Rect(x=cluster_legend_x, y=y_pos, width=10, height=10, fill=color)
)
_axes.append(
Text(x=cluster_legend_x + 18, y=y_pos + 10, text=label, class_="axis-label")
)
# ===== AGGREGATE FLOWERS (Bottom right area) =====
#create two groups
top_half = filtered_flowers.nlargest(len(filtered_flowers)//2, "Mean_CC_Yield")
bottom_half = filtered_flowers.nsmallest(len(filtered_flowers)//2, "Mean_CC_Yield")
# ABUNDANCE (for petal length)
g1_herb = bottom_half["Herb_abundance"].mean()
g1_bryo = bottom_half["Bryo_abundance"].mean()
g1_woody = bottom_half["Woody_abundance"].mean()
g2_herb = top_half["Herb_abundance"].mean()
g2_bryo = top_half["Bryo_abundance"].mean()
g2_woody = top_half["Woody_abundance"].mean()
# RICHNESS (for petal opacity)
g1_herb_richness = bottom_half["Veg_Spps"].mean()
g1_bryo_richness = bottom_half["Bryo_Spps"].mean()
g1_woody_richness = bottom_half["Woody_Spps"].mean()
g2_herb_richness = top_half["Veg_Spps"].mean()
g2_bryo_richness = top_half["Bryo_Spps"].mean()
g2_woody_richness = top_half["Woody_Spps"].mean()
#y positions fixed to mean yield of each group
flower_x = usable_width + 200
flower_y1 = top_margin + margin + (y_max - bottom_half["Mean_CC_Yield"].mean()) / (y_max - y_min) * usable_height #+800
flower_y2 = top_margin + margin + (y_max - top_half["Mean_CC_Yield"].mean()) / (y_max - y_min) * usable_height # + 900
#define draw_flower mentioning position, direction, abundance for two groups, colour etc
def draw_flower(cx, cy, herb, bryo, woody, herb_rich, bryo_rich, woody_rich, scale=1):
petals = [
(90, herb, "orange", herb_rich, herb_richness_min, herb_richness_max),
(210, bryo, "blue", bryo_rich, bryo_richness_min, bryo_richness_max),
(330, woody, "green", woody_rich, woody_richness_min, woody_richness_max),
]
flower_elements = []
for angle, abundance, color, richness, min_richness, max_richness in petals:
rad = math.radians(angle)
petal_length = abundance / 100 * 14 * scale
opacity = get_opacity_from_richness(richness, min_richness, max_richness)
ex = cx + math.sin(rad) * petal_length
ey = cy - math.cos(rad) * petal_length
flower_elements.append(
Ellipse(
cx=ex,
cy=ey,
rx=3 * scale,
ry=petal_length,
fill=color,
opacity=opacity,
transform=f"rotate({angle}, {ex}, {ey})"
)
)
return flower_elements
# draw both aggregate flowers using definition
_elements += draw_flower(flower_x, flower_y1, g1_herb, g1_bryo, g1_woody, g1_herb_richness, g1_bryo_richness, g1_woody_richness, scale=3)
_elements += draw_flower(flower_x, flower_y2, g2_herb, g2_bryo, g2_woody, g2_herb_richness, g2_bryo_richness, g2_woody_richness, scale=3)
#add labels
_axes.append(
Text(
x=legend_x#flower_x-60
, y=density_legend_y +235,
text="Aggregate flowers of two groups comparing low/high yield",
class_="axis-title"#,
#font_size=6
)
)
_axes.append(Text(
x=legend_x #flower_x-60
, y=flower_y1 - 60,
text="Sites with low yield (Lower half of 60 sites/Bottom 10)", class_="axis-label"#, font_size=7
))
_axes.append(Text(
x=legend_x,
#flower_x-60,
y=flower_y2 -60,
text="Sites with top yield (Upper half of 60 sites/Top 10)", class_="axis-label"#, font_size=7
))
# ===== DENSITY VISUALISATION BACKGROUND =====
#add values of structure index in a list to calculate gaps
struct_values = structureindex.values
for idx in range(len(struct_values) - 1):
gap = struct_values[idx + 1] - struct_values[idx]
#size of gap determines opacity
if gap == 0.0000:
opacity = 0.35
elif gap < 0.03:
opacity = 0.32
elif gap < 0.06:
opacity = 0.25
elif gap < 0.10:
opacity = 0.18
else:
opacity = 0.10
#define positions for drawing rectangle (in between sites)
x_curr = margin + (ordinal_pos[idx] / num_sites) * usable_width
x_next = margin + (ordinal_pos[idx + 1] / num_sites) * usable_width
#draw rectangles between each site/structure index value, that span across the whole y-axis, using opacity variable to change according to gap size
_axes.append(
Rect(x=x_curr, y=margin+ top_margin, width=x_next - x_curr,
height=usable_height, fill="gray", opacity=opacity)
)
# ===== CREATING SVG FRAME =====
_svg = SVG(width=svg_width, height=svg_height, class_="abc",
elements=_elements+_axes)
svg_str = _svg.as_str()
mo.vstack([
mo.Html(svg_str),
mo.hstack([
filter_selector,
flower_size
])
])
return (
abundance,
abundance_values,
angle,
arrow_tip_x,
arrow_tip_y,
bar_height,
bar_max_height,
bar_spacing,
bar_width,
bar_x,
bottom_half,
bryo_,
bryo_richness,
cluster,
cluster_colors,
cluster_dataa,
cluster_idx,
cluster_legend_x,
cluster_legend_y,
color,
count,
counts,
cx,
cy,
cy_max,
cy_min,
density_legend_y,
draw_flower,
ex,
ey,
flower_x,
flower_y1,
flower_y2,
frame_padding,
g1_bryo,
g1_bryo_richness,
g1_herb,
g1_herb_richness,
g1_woody,
g1_woody_richness,
g2_bryo,
g2_bryo_richness,
g2_herb,
g2_herb_richness,
g2_woody,
g2_woody_richness,
gap,
gap_values,
herb_,
herb_richness,
histogram_y,
i,
idx,
label,
legend_colors,
legend_x,
legend_y,
legend_y_abundance,
legend_y_richness,
margin,
max_richness,
max_y,
min_richness,
min_y,
num_sites,
opacities_richness,
opacity,
opacity_values,
ord_pos,
ord_pos_val,
petal_len,
petal_length,
petal_lengths,
petals,
rad,
richness,
richness_label,
richness_val,
richness_values,
site_,
site_id_,
site_x,
spacing,
struct_values,
structure_,
svg_str,
top_half,
top_margin,
usable_height,
usable_width,
val,
woody_,
woody_richness,
x,
x2_end,
x_curr,
x_max,
x_min,
x_next,
y,
y_max,
y_min,
y_pos,
yield_,
)
if __name__ == "__main__":
app.run()
import marimo
__generated_with = "0.11.26"
app = marimo.App(width="medium")
def _():
import marimo as mo
import pandas as pd
import math
from svg import SVG, Circle, Text, G, Line, Ellipse, Rect, Title
import numpy as np
return Circle, Ellipse, G, Line, Rect, SVG, Text, Title, math, mo, np, pd
def _(pd):
# ===== IMPORT DATASETS =====
coffeeyield = pd.read_excel("Coffee_yield.xlsx")
coffeestructureindex_management = pd.read_excel("Environmental_and_management_variables.xlsx")
plant_species_richness = pd.read_excel("Plant_species_richness.xlsx")
return coffeestructureindex_management, coffeeyield, plant_species_richness
def _(pd):
# ===== PREPARE WOODY DATA =====
#Load the excelfile
woody_species_abundance = pd.read_excel("Woody_species_abundance.xlsx")
woody_species_abundance
#Creating dataframe of total abundance of woody species, per Site ID
woody_totals = woody_species_abundance.iloc[:, 1:].sum().reset_index()
#Rename the columns to meaningful names
woody_totals.columns = ["Site ID", "Woody_total"]
#Normalise the abundance values to 0-100 scale for comparability
#Divide each value by max (0-1 scale) and multiply by 100 (0-100 scale)
woody_totals["Woody_abundance"] = (woody_totals["Woody_total"] / woody_totals["Woody_total"].max()) * 100
#Keep only the Site ID and normalised abundance columns
w_abundance = woody_totals[["Site ID", "Woody_abundance"]]
#w_abundance
return w_abundance, woody_species_abundance, woody_totals
def _(pd):
# ===== PREPARE BRYOPHYTE DATA =====
#Load the txtfile
bryophyte_species_abundance = pd.read_csv("Bryophyte_frequency.txt", sep="\t")
#Creating dataframe of total abundance of bryo species, per Site ID
bryo_totals = bryophyte_species_abundance.iloc[:, 1:].sum().reset_index()
#Rename the columns to meaningful names
bryo_totals.columns = ["Site ID", "Bryo_total"]
#Normalise the abundance values to 0-100 scale for comparability
#Divide each value by max (0-1 scale) and multiply by 100 (0-100 scale)
bryo_totals["Bryo_abundance"] = (bryo_totals["Bryo_total"] / bryo_totals["Bryo_total"].max()) * 100
#Keep only the Site ID and normalised abundance columns
b_abundance = bryo_totals[["Site ID", "Bryo_abundance"]]
#b_abundance
return b_abundance, bryo_totals, bryophyte_species_abundance
def _():
# # ===== VERIFY BRYOPHYTE DATA =====
# # See the raw totals BEFORE normalization
# print("Raw bryophyte totals (before normalization):")
# print(bryo_totals[["Site ID", "Bryo_total"]])
# # See which site has the max
# print(f"\nMax bryo total: {bryo_totals['Bryo_total'].max()}")
# # Check a specific site (e.g., Ge1)
# ge1_row = bryo_totals[bryo_totals["Site ID"] == "Ge1"]
# if not ge1_row.empty:
# ge1_raw = ge1_row["Bryo_total"].values[0]
# print(f"Ge1 raw total: {ge1_raw}")
# # Verify the normalization calculation manually
# ge1_normalized_manual = (ge1_raw / bryo_totals["Bryo_total"].max()) * 100
# ge1_normalized_actual = ge1_row["Bryo_abundance"].values[0]
# print(f"Ge1 normalized (manual calc): {ge1_normalized_manual:.2f}")
# print(f"Ge1 normalized (from data): {ge1_normalized_actual:.2f}")
# print(f"Match: {abs(ge1_normalized_manual - ge1_normalized_actual) < 0.01}")
# else:
# print("Ge1 not found in data")
# # Show distribution