# /// script # requires-python = ">=3.11" # dependencies = [ # "marimo>=0.23.1", # "numpy==2.4.4", # "pandas==3.0.2", # "svgwrite>=1.4.3", # "openpyxl>=3.1.0", # "cairosvg==2.9.0", # ] # /// import marimo __generated_with = "0.23.0" app = marimo.App( width="full", css_file="/usr/local/_marimo/custom.css", auto_download=["html"], ) @app.cell def _(): import math from pathlib import Path import marimo as mo import numpy as np import pandas as pd import svgwrite return Path, math, mo, np, pd, svgwrite @app.cell def _(mo): mo.md(r"""
Marimo · SVG · HTML/CSS

Coffee sites visualization

This marimo notebook shows our visualization for the coffeesites

""") return @app.cell def _(Path, mo): # ===== Input/output paths for Hugging Face Spaces ===== # Primary location requested for local runs in this environment. DATA_FILENAME = "merged_species_dataset.xlsx" default_candidates = [ Path("data") / DATA_FILENAME, Path.cwd() / DATA_FILENAME, Path(__file__).resolve().parent / DATA_FILENAME, ] # Automatically use the first existing dataset path. If none exists, keep # data/data_species_merged.xlsx as the displayed default so the error # message clearly shows the expected file location. default_file = next((p for p in default_candidates if p.exists()), default_candidates[0]) # Write generated figures to a local outputs folder. This works both in # /data and in Hugging Face Spaces. output_dir = Path("outputs") output_dir.mkdir(exist_ok=True) default_stem = output_dir / "coffee_sites_visualisation_marimo" # Keep the path visible but pre-filled automatically. data_path = mo.ui.text( value=str(default_file), label="Excel dataset path", full_width=True, ) export_png = mo.ui.checkbox( value=False, label="Also export PNG (optional; requires cairosvg)", ) output_stem = mo.ui.text( value=str(default_stem), label="Output file stem", full_width=True, ) mo.vstack( [ mo.md( '
' '
Inputs
' '
The notebook automatically looks for data_species_merged.xlsx in data, the current working directory, and the app folder. For Hugging Face Spaces, place the Excel file next to this Python file or keep the shown path if you mount data there.
' '
' ), data_path, mo.hstack( [export_png, output_stem], justify="start", gap=1.5, ), ] ) return data_path, export_png, output_stem @app.cell def _(): # ===== DATA setup ===== YEAR_COLUMNS = ["CC_Yield_2017", "CC_Yield_2018", "CC_Yield_2019"] MEAN_COLUMN = "Mean_CC_Yield" CSI_COLUMN = "Coffee structure index" SITE_COLUMN = "Site_ID" SPECIES_GROUPS = [ # This is a list of dictionaries for the biodiversity panel { "name": "Woody", "richness_col": "Woody_Spps", "abundance_col": "Woody_abundance", "sum_col": "woody_amount", "x_col": "woody_x", "color": "#3B7A57", }, { "name": "Herbaceous", "richness_col": "Veg_Spps", "abundance_col": "Herbaceous_abundance", "sum_col": "herbaceous_amount", "x_col": "herbaceous_x", "color": "#5AA9E6", }, { "name": "Bryophyte", "richness_col": "Bryo_Spps", "abundance_col": "Bryophyte_frequency", "sum_col": "bryophyte_amount", "x_col": "bryophyte_x", "color": "#D9B44A", }, ] # ===== COLOR PALETTE FOR THE VISUALIZATION ===== PALETTE = { "text": "#1F2937", "muted": "#6B7280", "axis": "#5D554B", "grid": "#D9D2C6", "background": "#F7F4EE", "card": "#FFFDF9", "card_cap": "#F3ECE1", "row": "#ECE7DE", "year_2017": "#C9D6EA", "year_2018": "#93B5E1", "year_2019": "#4E79A7", "mean": "#1F2937", "csi": "#D97B66", "accent": "#6F4E37", } return ( CSI_COLUMN, MEAN_COLUMN, PALETTE, SITE_COLUMN, SPECIES_GROUPS, YEAR_COLUMNS, ) @app.cell def _(Path, data_path, mo, pd): # ====== DATA loading ====== xlsx_path = Path(data_path.value) if not xlsx_path.exists(): mo.stop( True, mo.md( f'
' f'
Dataset not found
' f'
The file {xlsx_path} does not exist. Update the input path above and rerun.
' f'
' ), ) site_df = pd.read_excel(xlsx_path, sheet_name="site_level_merged") long_df = pd.read_excel(xlsx_path, sheet_name="all_data_long") return long_df, site_df, xlsx_path @app.cell def _(long_df, mo, site_df): mo.accordion( { "Data preview": mo.vstack( [ mo.md( f'
' f'Loaded rows: {len(site_df)} site-level rows and {len(long_df)} long-table rows.' f'
' ), mo.hstack([site_df.head(), long_df.head()], widths=[1, 1]), ] ) } ) return @app.cell def _( CSI_COLUMN, MEAN_COLUMN, SITE_COLUMN, SPECIES_GROUPS, YEAR_COLUMNS, long_df, math, pd, site_df, ): def build_plot_table(site_df: pd.DataFrame, long_df: pd.DataFrame) -> pd.DataFrame: df = site_df.copy() # we group the data by site and then sum abundance values per site gving a summary row per side with # the total abundance values abundance_table = long_df.groupby(SITE_COLUMN).agg( woody_amount=("Woody_abundance", "sum"), herbaceous_amount=("Herbaceous_abundance", "sum"), bryophyte_amount=("Bryophyte_frequency", "sum"), ) # Merge the summed abundance values into the site-level table # left_on=SITE_COLUMN means use the Site_ID column from df # right_index=True means use the index of abundance_table (the grouped site IDs) # how="left" means keep all rows from df even if some sites have missing abundance data df = df.merge(abundance_table, left_on=SITE_COLUMN, right_index=True, how="left") # Build a list of all columns that should be treated as numeric # This includes yearly yields, mean yield, CSI, richness columns, and the new abundance-sum columns numeric_cols = YEAR_COLUMNS + [MEAN_COLUMN, CSI_COLUMN] + [ g["richness_col"] for g in SPECIES_GROUPS ] + [g["sum_col"] for g in SPECIES_GROUPS] # Convert all those columns to numeric values # errors="coerce" means invalid values are turned into NaN instead of crashing for col in numeric_cols: df[col] = pd.to_numeric(df[col], errors="coerce") # For each species group, create a standardized richness value between 0 and 1. # This is used to place biodiversity bubbles horizontally in the chart. # Bubble size is now controlled by abundance instead. for group in SPECIES_GROUPS: series = df[group["richness_col"]] # Get the richness values for this species group min_val = series.min() # Find the minimum and maximum richness across all sites max_val = series.max() # If values are missing, or all values are the same, # place everything at 0.5 (so in the middle of the axis) to avoid division errors if pd.isna(min_val) or pd.isna(max_val) or math.isclose(min_val, max_val): df[group["x_col"]] = 0.5 else: # Standardize richness to the range 0–1 using min-max normalization df[group["x_col"]] = (series - min_val) / (max_val - min_val) # Sort sites from highest to lowest mean yield # reset_index(drop=True) gives the table a clean new row index df = df.sort_values(MEAN_COLUMN, ascending=False).reset_index(drop=True) return df plot_df = build_plot_table(site_df, long_df) return (plot_df,) @app.cell def _(MEAN_COLUMN, SITE_COLUMN, SPECIES_GROUPS, mo, plot_df): # ===== CALCULATE SUMMARY STATISTICS ===== n_sites = len(plot_df) # Total number of sites yield_min = float(plot_df[MEAN_COLUMN].min()) # Minimum mean yield across all sites yield_max = float(plot_df[MEAN_COLUMN].max()) # Maximum mean yield across all sites # Find the largest species richness value across ALL species groups # For each group, take its richness column, find its max, then take the overall max richest = max(float(plot_df[g["richness_col"]].max()) for g in SPECIES_GROUPS) # Get the site with the highest mean yield # plot_df is already sorted (highest first), so we take the first row # If there are no sites, show a dash instead top_site = str(plot_df.iloc[0][SITE_COLUMN]) if n_sites else "—" # ===== BUILD HTML FOR DISPLAY ===== # Create an HTML string using f-string formatting # This inserts the calculated values directly into the HTML stats_html = f"""
Sites
{n_sites}
Sorted by mean coffee yield
Top site
{top_site}
Highest mean yield in the figure
Mean yield range
{yield_min:,.0f}–{yield_max:,.0f}
Across site-level means
Largest richness
{richest:,.0f}
Maximum species richness encoded by bubble location before min-max scaling
""" mo.Html(stats_html) # Needed to render the HTML in the marimo notebook return @app.cell def _(math, pd): def scale_linear(value: float, domain: tuple[float, float], rng: tuple[float, float]) -> float: # Unpack the input range (domain) → the range of your data d0, d1 = domain # Unpack the output range → the range on the screen (so the pixel positions) r0, r1 = rng # If the value is missing (NaN), return NaN # This prevents errors later when plotting if pd.isna(value): return float("nan") # If the input range has no variation (min == max), # avoid division by zero by placing the value in the middle of the output range if math.isclose(d0, d1): return (r0 + r1) / 2 # Perform linear scaling (min-max normalization + stretching to new range) return r0 + (value - d0) * (r1 - r0) / (d1 - d0) return (scale_linear,) @app.cell def _( CSI_COLUMN, MEAN_COLUMN, PALETTE, SITE_COLUMN, SPECIES_GROUPS, YEAR_COLUMNS, np, pd, scale_linear, svgwrite, ): class CoffeeSiteFigure: # this class is used for building the full SVG figure def __init__(self, df: pd.DataFrame): self.df = df self.font = 'Inter, "Segoe UI", Arial, sans-serif' # Fonts used in the SVG text self.tooltip_font = 'Inter, "Segoe UI", Arial, sans-serif' self.margin = {"top": 110, "right": 44, "bottom": 118, "left": 104} # Margins around the full # figure (top, right, bottom, # left) self.row_h = 18 # Vertical size of each site row self.site_gap = 10 # Vertical gap between rows self.panel_gap = 28 # Horizontal gap between the 3 panels self.site_label_gap = 12 # Space between site labels and the first panel self.year_bar_h = 3.4 # Heights of the year bars self.mean_bar_h = 4.2 # Mean bar in panel 1 self.panel1_w = 340 # Width of panel 1 self.panel2_w = 190 # Width of panel 2 self.panel3_w = 390 # Width of panel 3 # Total figure width: # left margin + panel 1 + gap + panel 2 + gap + panel 3 + right margin self.width = ( self.margin["left"] + self.panel1_w + self.panel_gap + self.panel2_w + self.panel_gap + self.panel3_w + self.margin["right"] ) # x-position where each panel begins self.x1 = self.margin["left"] self.x2 = self.x1 + self.panel1_w + self.panel_gap self.x3 = self.x2 + self.panel2_w + self.panel_gap # y-position for the panel header area self.y0 = self.margin["top"] # Top axis labels should sit below each panel title/subtitle, # not above the panel header. The data rows start lower so the # top axis does not overlap the first site row. self.top_axis_label_y = self.y0 + 22 self.top_axis_line_y = self.y0 + 29 self.data_y0 = self.y0 + 38 # Height occupied by all site rows self.rows_h = len(df) * (self.row_h + self.site_gap) - self.site_gap # Bottom of the plotting area self.plot_bottom = self.data_y0 + self.rows_h # Total figure height: # plot bottom + bottom margin self.height = self.plot_bottom + self.margin["bottom"] # Data ranges used for scaling values onto the chart self.yield_min = 0 self.yield_max = float(np.nanmax(df[YEAR_COLUMNS + [MEAN_COLUMN]].to_numpy())) # Fixed CSI scale used in panel 2 self.csi_min = 1 self.csi_max = 3 # Minimum and maximum bubble radius for biodiversity points self.size_min = 4 self.size_max = 12 # Collect the abundance-total columns for all species groups abundance_cols = [g["sum_col"] for g in SPECIES_GROUPS] # Find the overall minimum and maximum abundance values across all groups. # These values now control biodiversity bubble size. self.abundance_min = float(df[abundance_cols].min().min()) self.abundance_max = float(df[abundance_cols].max().max()) # Return the vertical center position for a site row def site_y(self, idx: int) -> float: return self.data_y0 + idx * (self.row_h + self.site_gap) + self.row_h / 2 # Convert a yield value into an x-position inside panel 1 def yield_x(self, value: float) -> float: return scale_linear(value, (self.yield_min, self.yield_max), (self.x1, self.x1 + self.panel1_w)) # Convert a CSI value into an x-position inside panel 2 def csi_x(self, value: float) -> float: return scale_linear(value, (self.csi_min, self.csi_max), (self.x2, self.x2 + self.panel2_w)) # Convert a standardized biodiversity value (0 to 1) into an x-position inside panel 3 def bio_x(self, value: float) -> float: return scale_linear(value, (0, 1), (self.x3, self.x3 + self.panel3_w)) # Convert an abundance value into a bubble radius def bubble_r(self, value: float) -> float: return scale_linear(value, (self.abundance_min, self.abundance_max), (self.size_min, self.size_max)) # Attach a tooltip/title to an SVG element --> shows up later on hover def _add_title(self, element, text: str): element.set_desc(title=text) return element # Main drawing method: creates the SVG and calls all sub-drawing methods def draw(self, output_svg): # Create an SVG drawing object with the full figure size dwg = svgwrite.Drawing(str(output_svg), size=(self.width, self.height)) # Set the viewbox so the SVG scales properly dwg.viewbox(0, 0, self.width, self.height) # Add a CSS class so the SVG can be styled from the notebook CSS dwg.attribs["class"] = "coffee-sites-svg" # Embed the SVG styling directly in the exported SVG. # This is important because downloaded SVG/PNG files cannot rely on # the notebook page CSS. Without these embedded styles, some SVG # viewers render class-based fills as black. dwg.defs.add( dwg.style( """ .coffee-sites-svg .row-line { stroke: #ECE7DE; stroke-width: 1; } .coffee-sites-svg .panel-card { fill: #FFFDFA; stroke: #E1D7C9; stroke-width: 1; } .coffee-sites-svg .panel-cap { fill: #F3ECE1; } .coffee-sites-svg .grid-line { stroke: #D9D2C6; stroke-width: 0.9; stroke-dasharray: 4 4; vector-effect: non-scaling-stroke; } .coffee-sites-svg .axis-line { stroke: #5D554B; stroke-width: 1.2; vector-effect: non-scaling-stroke; } .coffee-sites-svg .yield-bar, .coffee-sites-svg .csi-bar, .coffee-sites-svg .bio-bubble { cursor: pointer; } """ ) ) # Draw a full solid background rectangle so exported SVG/PNG files # never fall back to a transparent or black background. dwg.add( dwg.rect( insert=(0, 0), size=(self.width, self.height), fill=PALETTE["background"], stroke="none", ) ) # Draw the different parts of the figure in order self._draw_shell(dwg) self._draw_title(dwg) self._draw_panel_headers(dwg) self._draw_reference_grid(dwg) self._draw_vertical_axes(dwg) self._draw_sites(dwg) self._draw_legends(dwg) self._draw_footer(dwg) dwg.save() # Draw background cards & panels behind the 3 chart sections def _draw_shell(self, dwg): # Keep one shared geometry for all three panels so their backgrounds, # header bands, and plot areas line up exactly. panel_top = self.y0 - 36 panel_bottom = self.plot_bottom + 18 panel_h = panel_bottom - panel_top # Header band height is tall enough to contain title, subtitle, # top-axis labels, and the top-axis line. # It uses only top-rounded corners; the bottom edge is straight, # which avoids uneven curved overlaps between the panel header boxes. header_h = (self.top_axis_line_y + 8) - panel_top corner_r = 16 panels = [ (self.x1 - 14, self.panel1_w + 28), (self.x2 - 14, self.panel2_w + 28), (self.x3 - 14, self.panel3_w + 28), ] for x, w in panels: # Main rounded panel body dwg.add( dwg.rect( insert=(x, panel_top), size=(w, panel_h), rx=corner_r, ry=corner_r, class_="panel-card", ) ) # Top header band with rounded top corners only and a straight bottom. cap_path = dwg.path( d=( f"M {x},{panel_top + header_h} " f"L {x},{panel_top + corner_r} " f"Q {x},{panel_top} {x + corner_r},{panel_top} " f"L {x + w - corner_r},{panel_top} " f"Q {x + w},{panel_top} {x + w},{panel_top + corner_r} " f"L {x + w},{panel_top + header_h} Z" ), class_="panel-cap", ) dwg.add(cap_path) # Draw the big figure title at the top def _draw_title(self, dwg): dwg.add( dwg.text( "Coffee sites: yield, structure, and biodiversity", insert=(self.margin["left"], 38), font_size=24, font_family=self.font, font_weight=700, fill=PALETTE["text"], ) ) # Draw section headers above the 3 panels def _draw_panel_headers(self, dwg): headers = [ (self.x1, self.panel1_w, "Yield per site", "2017, 2018, 2019, and mean"), (self.x2, self.panel2_w, "Coffee structure index", "Single bar per site"), (self.x3, self.panel3_w, "Biodiversity", "x = standardized richness · size = abundance"), ] for x, w, title, subtitle in headers: # Header title dwg.add( dwg.text( title, insert=(x, self.y0 - 16), font_size=13, font_family=self.font, font_weight=700, fill=PALETTE["text"], ) ) # Header subtitle dwg.add( dwg.text( subtitle, insert=(x, self.y0 - 2), font_size=10.5, font_family=self.font, fill=PALETTE["muted"], ) ) # Thin separator line under header dwg.add( dwg.line( start=(x, self.y0 + 8), end=(x + w, self.y0 + 8), stroke=PALETTE["grid"], stroke_width=1, ) ) # Draw the vertical baseline axis for each panel def _draw_vertical_axes(self, dwg): y1 = self.top_axis_line_y # Extend the vertical axes slightly below the plotting rows. # This moves the arrowheads out of the data area so they do not # overlap the last site row. axis_extension = 16 y2 = self.plot_bottom + axis_extension for x in [self.x1, self.x2, self.x3]: dwg.add(dwg.line(start=(x, y1), end=(x, y2), class_="axis-line")) dwg.add( dwg.polygon( points=[(x - 4, y2 - 8), (x + 4, y2 - 8), (x, y2)], fill=PALETTE["axis"], ) ) # Draw vertical reference/grid lines and tick labels in each panel def _draw_reference_grid(self, dwg): # Top axis baselines, placed below the panel title/subtitle for x, w in [ (self.x1, self.panel1_w), (self.x2, self.panel2_w), (self.x3, self.panel3_w), ]: dwg.add( dwg.line( start=(x, self.top_axis_line_y), end=(x + w, self.top_axis_line_y), class_="axis-line", ) ) # Panel 1: yield ticks for tick in np.linspace(self.yield_min, self.yield_max, 5): x = self.yield_x(float(tick)) dwg.add(dwg.line(start=(x, self.top_axis_line_y), end=(x, self.plot_bottom), class_="grid-line")) # Bottom axis label dwg.add( dwg.text( f"{tick:,.0f}", insert=(x, self.plot_bottom + 30), text_anchor="middle", font_size=10, font_family=self.font, fill=PALETTE["muted"], ) ) # Top axis label dwg.add( dwg.text( f"{tick:,.0f}", insert=(x, self.top_axis_label_y), text_anchor="middle", font_size=10, font_family=self.font, fill=PALETTE["muted"], ) ) # Panel 2: CSI ticks for tick in [1, 2, 3]: x = self.csi_x(tick) dwg.add(dwg.line(start=(x, self.top_axis_line_y), end=(x, self.plot_bottom), class_="grid-line")) # Bottom axis label dwg.add( dwg.text( str(tick), insert=(x, self.plot_bottom + 30), text_anchor="middle", font_size=10, font_family=self.font, fill=PALETTE["muted"], ) ) # Top axis label dwg.add( dwg.text( str(tick), insert=(x, self.top_axis_label_y), text_anchor="middle", font_size=10, font_family=self.font, fill=PALETTE["muted"], ) ) # Panel 3: biodiversity axis labels for tick, label in zip([0, 0.5, 1.0], ["low", "mid", "high"]): x = self.bio_x(tick) dwg.add(dwg.line(start=(x, self.top_axis_line_y), end=(x, self.plot_bottom), class_="grid-line")) # Bottom axis label dwg.add( dwg.text( label, insert=(x, self.plot_bottom + 30), text_anchor="middle", font_size=10, font_family=self.font, fill=PALETTE["muted"], ) ) # Top axis label dwg.add( dwg.text( label, insert=(x, self.top_axis_label_y), text_anchor="middle", font_size=10, font_family=self.font, fill=PALETTE["muted"], ) ) # Draw all site rows: labels, yield bars, CSI bars, and biodiversity bubbles def _draw_sites(self, dwg): # Colors for the 3 yearly yield bars year_colors = [PALETTE["year_2017"], PALETTE["year_2018"], PALETTE["year_2019"]] bar_offsets = [-5.5, -1.7, 2.1, 6.2] # Small vertical offsets so the four bars do not overlap # Loop through each site row in the dataframe for i, row in self.df.iterrows(): # Vertical position for this site y = self.site_y(i) # Horizontal row separator line dwg.add( dwg.line( start=(self.x1 - 10, y), end=(self.x3 + self.panel3_w + 8, y), class_="row-line", ) ) # Site label shown to the left of the first panel dwg.add( dwg.text( str(row[SITE_COLUMN]), insert=(self.x1 - self.site_label_gap, y + 3.6), text_anchor="end", font_size=10.5, font_family=self.font, font_weight=600, fill=PALETTE["text"], ) ) # Gather yearly yield values plus mean yield values = [row[c] for c in YEAR_COLUMNS] + [row[MEAN_COLUMN]] # Colors, heights, and text labels for those 4 bars colors = year_colors + [PALETTE["mean"]] heights = [self.year_bar_h, self.year_bar_h, self.year_bar_h, self.mean_bar_h] labels = ["2017", "2018", "2019", "Mean"] # Draw each yield bar for v, color, h, off, label in zip(values, colors, heights, bar_offsets, labels): if pd.isna(v): continue x_end = self.yield_x(float(v)) # Draw horizontal bar from left axis to scaled x-position rect = dwg.rect( insert=(self.x1, y + off - h / 2), size=(max(0, x_end - self.x1), h), fill=color, rx=1.6, ry=1.6, class_="yield-bar", opacity=0.94, ) # Add tooltip text self._add_title(rect, f"Site {row[SITE_COLUMN]} · {label} yield: {float(v):,.2f}") dwg.add(rect) # Draw the CSI bar csi = row[CSI_COLUMN] if not pd.isna(csi): x_end = self.csi_x(float(csi)) rect = dwg.rect( insert=(self.x2, y - 3.9), size=(max(0, x_end - self.x2), 7.8), fill=PALETTE["csi"], rx=2, ry=2, class_="csi-bar", opacity=0.92, ) self._add_title(rect, f"Site {row[SITE_COLUMN]} · Coffee structure index: {float(csi):.2f}") dwg.add(rect) # Draw biodiversity bubbles for the 3 species groups # All biodiversity circles for a site are aligned on the same horizontal row. for group in SPECIES_GROUPS: richness = row[group["richness_col"]] abundance = row[group["sum_col"]] x_std = row[group["x_col"]] # Skip missing values if pd.isna(richness) or pd.isna(abundance) or pd.isna(x_std): continue # Draw one circle for this group bubble = dwg.circle( center=(self.bio_x(float(x_std)), y), r=self.bubble_r(float(abundance)), fill=group["color"], fill_opacity=0.78, stroke="white", stroke_width=1, class_="bio-bubble", ) # Add tooltip text with more detail self._add_title( bubble, ( f"Site {row[SITE_COLUMN]} · {group['name']}\n" f"Standardized richness: {float(x_std):.2f}\n" f"Richness: {float(richness):.0f}\n" f"Abundance: {float(abundance):,.0f}" ), ) dwg.add(bubble) # Draw the legends at the bottom of the figure def _draw_legends(self, dwg): # Give the legend a little more vertical space so labels do not overlap. # Row 1: year legend + biodiversity group legend. # Row 2: bubble-size key for the biodiversity panel. legend_y = self.height - 72 bubble_key_y = self.height - 46 # Legend for yearly yield colors + mean for idx, (color, label) in enumerate([ (PALETTE["year_2017"], "2017"), (PALETTE["year_2018"], "2018"), (PALETTE["year_2019"], "2019"), (PALETTE["mean"], "Mean"), ]): x = self.x1 + idx * 62 dwg.add(dwg.rect(insert=(x, legend_y - 10), size=(18, 8), fill=color, rx=2, ry=2)) dwg.add( dwg.text( label, insert=(x + 24, legend_y - 3), font_size=10.5, font_family=self.font, fill=PALETTE["text"], ) ) # Legend for the biodiversity groups # Use slightly tighter spacing and keep this on its own row. for idx, group in enumerate(SPECIES_GROUPS): x = self.x3 + idx * 100 dwg.add( dwg.circle( center=(x + 7, legend_y - 5), r=5.5, fill=group["color"], fill_opacity=0.78, ) ) dwg.add( dwg.text( group["name"], insert=(x + 18, legend_y - 1.5), font_size=10.5, font_family=self.font, fill=PALETTE["text"], ) ) # Bubble size key on a separate row to prevent overlap with the group labels. key_x = self.x3 dwg.add(dwg.circle(center=(key_x + 7, bubble_key_y - 5), r=4.5, fill="none", stroke=PALETTE["muted"], stroke_width=1)) dwg.add(dwg.circle(center=(key_x + 36, bubble_key_y - 5), r=9.5, fill="none", stroke=PALETTE["muted"], stroke_width=1)) dwg.add( dwg.text( "Bubble size = abundance", insert=(key_x + 54, bubble_key_y - 1.5), font_size=10.5, font_family=self.font, fill=PALETTE["muted"], ) ) # Draw small footer text at the bottom def _draw_footer(self, dwg): dwg.add( dwg.text( "Hover over bars and bubbles for exact values.", insert=(self.margin["left"], self.height - 18), font_size=10, font_family=self.font, fill=PALETTE["muted"], ) ) return (CoffeeSiteFigure,) @app.cell def _( CoffeeSiteFigure, PALETTE, Path, export_png, mo, output_stem, plot_df, xlsx_path, ): # output paths output_svg = Path(f"{output_stem.value}.svg") output_png = Path(f"{output_stem.value}.png") # drawing the figure figure = CoffeeSiteFigure(plot_df) figure.draw(output_svg) png_message = "PNG export skipped." if export_png.value: try: import cairosvg # type: ignore cairosvg.svg2png( url=str(output_svg), write_to=str(output_png), dpi=220, background_color=PALETTE["background"], ) png_message = f"PNG written to `{output_png}`" except Exception as exc: # pragma: no cover png_message = f"PNG export skipped: {exc}" # Build the final HTML preview shown inside the notebook preview_html = f"""
Final figure

Excel input: {xlsx_path}
SVG written to {output_svg}
{png_message}

{output_svg.read_text(encoding='utf-8')}
""" mo.Html(preview_html) return if __name__ == "__main__": app.run()