A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
examples: cleanup marimo-widget examples (#2164)
Myles Scolnicke089490fd621
diff --git a/examples/marimo/batch_and_form.py b/examples/marimo/batch_and_form.pyindex e597097d8c..7747b55311 100644--- a/examples/marimo/batch_and_form.py+++ b/examples/marimo/batch_and_form.py@@ -1,12 +1,12 @@import marimo-__generated_with = "0.1.0"+__generated_with = "0.8.5"app = marimo.App()@app.celldef __(mo):- mo.md("# Batch and Form")+ mo.md("""# Batch and Form""")return@@ -29,9 +29,9 @@ def __(mo, reset):mo.md("""Choose your variable values-+{x}-+{y}""")@@ -39,7 +39,7 @@ def __(mo, reset):x=mo.ui.slider(start=1, stop=10, step=1, label="$x =$"),y=mo.ui.slider(start=1, stop=10, step=1, label="$y =$"),)- .form()+ .form(show_clear_button=True, bordered=False))variables@@ -63,8 +63,7 @@ def __(mo, reset, submitted_values, variables):All values ever assumed by $x$ and $y$ are- {mo.hstack([mo.tree(submitted_values), reset],- justify="start", align="center", gap=4)}+ {mo.hstack([mo.tree(submitted_values), reset], align="center", gap=4)}""").callout()return x, y@@ -74,10 +73,7 @@ def __(mo, reset, submitted_values, variables):def __(reset):reset- submitted_values = {- "x": set(),- "y": set()- }+ submitted_values = {"x": set(), "y": set()}return submitted_values,diff --git a/examples/marimo/data_explorer.py b/examples/marimo/data_explorer.pyindex 59694afb5c..8634ab426f 100644--- a/examples/marimo/data_explorer.py+++ b/examples/marimo/data_explorer.py@@ -1,7 +1,17 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "marimo",+# "pandas",+# "matplotlib",+# "altair",+# ]+# ///+import marimo-__generated_with = "0.8.0"-app = marimo.App()+__generated_with = "0.8.5"+app = marimo.App(width="full")@app.cell@@ -12,25 +22,27 @@ def __(mo):@app.celldef __(mo):- mo.md("""This notebook lets you upload a CSV and plot its columns.""")- return+ sample = "https://github.com/vega/vega/blob/main/docs/data/stocks.csv"+ mo.md(+ f"""+ This notebook lets you upload a CSV and plot its columns.-def __(df, mo, uploaded_file):- callout_kind = (- "alert"- if (uploaded_file.name() is None)- else "neutral"+ You can download a <a href="{sample}" target="_blank">sample CSV</a> if you'd like.+ """)+ return sample,+++def __(mo, uploaded_file):+ callout_kind = "alert" if (uploaded_file.name() is None) else "neutral"mo.md(f"""{mo.hstack([mo.md("**Upload a CSV.**")], justify="center")}{uploaded_file}-- {mo.as_html(df.head()) if df is not None else ""}""").callout(kind=callout_kind)return callout_kind,@@ -38,50 +50,57 @@ def __(df, mo, uploaded_file):@app.celldef __(io, mo, pd, uploaded_file):- df = None- columns = None+ mo.stop(not uploaded_file.name())+ df = pd.read_csv(io.StringIO(uploaded_file.contents().decode()))+ return df,+++def __(df, mo):+ mo.ui.table(df, page_size=5, selection=None)+ return+++def __(df, mo):plot_type = mo.ui.dropdown(["line", "hist"], value="line", label="Choose a plot type: ")- if uploaded_file.name() is not None:- df = pd.read_csv(io.StringIO(uploaded_file.contents().decode()))- columns = mo.ui.dropdown(df.columns[1:], label="Choose a column: ")- return columns, df, plot_type+ x_column = mo.ui.dropdown(df.columns, label="Choose x-axis: ")+ y_column = mo.ui.dropdown(df.columns, label="Choose y-axis: ")+ color_column = mo.ui.dropdown(df.columns, label="Choose color-axis: ")+ return color_column, plot_type, x_column, y_column@app.cell-def __(columns, mo, plot_type):- def column_selector():- if columns is None:- return None-- return mo.hstack([columns, plot_type], justify="space-around").callout(- kind="warn" if columns.value is None else "neutral"- )-- column_selector()- return column_selector,+def __(color_column, mo, plot_type, x_column, y_column):+ mo.hstack(+ [x_column, y_column, color_column, plot_type], justify="space-around"+ ).callout(kind="warn" if not x_column.value else "neutral")+ return@app.cell-def __(columns, df, plot_type, plt):- def plot_data():- if df is not None and columns.value is not None:- data = df[columns.value].to_numpy()- if plot_type.value == "line":- plt.plot(data)- else:- plt.hist(data)- plt.title(columns.value)- return plt.gca()+def __(alt, color_column, df, mo, plot_type, x_column, y_column):+ mo.stop(not x_column.value)+++ def plot(x_column, y_column, color_column):+ y_column = y_column or "count()"+ title = f"{y_column} by {x_column}"+ encoding = {"x": x_column, "y": y_column}+ if color_column:+ encoding["color"] = color_column+ if plot_type.value == "line":+ chart = alt.Chart(df).mark_line()else:- return None+ chart = alt.Chart(df).mark_bar().encode(x=alt.X(x_column, bin=True))+ return chart.encode(**encoding).properties(title=title, width="container")- plot = plot_data()- plot- return plot, plot_data+ plot(x_column.value, y_column.value, color_column.value)+ return plot,@app.cell@@ -93,11 +112,13 @@ def __(mo):@app.celldef __():import marimo as mo+ import altair as alt+import ioimport matplotlib.pyplot as pltimport pandas as pd- return io, mo, pd, plt+ return alt, io, mo, pd, pltif __name__ == "__main__":diff --git a/examples/marimo/filterable_table.py b/examples/marimo/filterable_table.pynew file mode 100644index 0000000000..5d6e13950d--- /dev/null+++ b/examples/marimo/filterable_table.py@@ -0,0 +1,86 @@+import marimo++__generated_with = "0.8.5"+app = marimo.App(width="medium")+++def __(mo):+ mo.md(r"""# Filterable DataFrame""")+ return+++def __(data_url, pd):+ # Read the csv+ df = pd.read_json(data_url("cars.json"))+ return df,+++def __(df):+ # Create options for select widgets+ manufacturer_options = df["Name"].str.split().str[0].unique()+ manufacturer_options.sort()+ cylinder_options = df["Cylinders"].unique().astype(str)+ cylinder_options.sort()+ return cylinder_options, manufacturer_options+++def __(cylinder_options, df, manufacturer_options, mo):+ # Create the filters+ manufacturer = mo.ui.dropdown(manufacturer_options, label="Manufacturer")+ cylinders = mo.ui.dropdown(cylinder_options, label="Cylinders")++ horse_power = mo.ui.range_slider.from_series(+ df["Horsepower"],+ show_value=True,+ )++ mo.hstack([manufacturer, horse_power, cylinders], gap=3).left()+ return cylinders, horse_power, manufacturer+++def __(df, filter_df):+ filter_df(df)+ return+++def __(cylinders, horse_power, manufacturer):+ def filter_df(df):+ filtered_df = df+ if manufacturer.value:+ filtered_df = filtered_df[+ filtered_df["Name"].str.contains(manufacturer.value, case=False)+ ]+ if cylinders.value:+ filtered_df = filtered_df[filtered_df["Cylinders"] == cylinders.value]+ if horse_power.value:+ left, right = horse_power.value+ filtered_df = filtered_df[+ (filtered_df["Horsepower"] >= left)+ & (filtered_df["Horsepower"] <= right)+ ]+ return filtered_df+ return filter_df,+++def __():+ def data_url(file):+ return f"https://cdn.jsdelivr.net/npm/[email protected]/data/{file}"+ return data_url,+++def __():+ import marimo as mo+ import pandas as pd+ return mo, pd+++if __name__ == "__main__":+ app.run()diff --git a/examples/marimo/inputs.py b/examples/marimo/inputs.pynew file mode 100644index 0000000000..bdb201f1cd--- /dev/null+++ b/examples/marimo/inputs.py@@ -0,0 +1,204 @@+import marimo++__generated_with = "0.8.5"+app = marimo.App(width="medium")+++def __(mo):+ mo.md(+ r"""+ # Inputs++ There are many way that a user can input with your notebook, such as text boxes, sliders, dates, and more.+ """+ )+ return+++def __(mo):+ mo.md(r"""## Text boxes""")+ return+++def __(mo):+ mo.hstack(+ [+ username := mo.ui.text(label="Username"),+ email := mo.ui.text(label="Email", kind="email"),+ mo.ui.text(label="Password", kind="password"),+ ]+ )+ return email, username+++def __(mo, username):+ mo.stop(not username.value, mo.md("What is your name?"))++ mo.md(f"👋 Hello {username.value}, nice to meet you!")+ return+++def __(mo):+ mo.ui.text_area(+ label="A space for your thoughts", full_width=True, max_length=1000+ )+ return+++def __(mo):+ mo.ui.number(label="What is your favorite number?", start=0, stop=10)+ return+++def __(mo):+ mo.md(r"""## Sliders""")+ return+++def __(mo):+ slider = mo.ui.slider(0, 100, value=50, label="Basic slider", show_value=True)+ range_slider = mo.ui.range_slider(+ 0, 100, value=(30, 70), label="Range slider", show_value=True+ )+ custom_steps = mo.ui.slider(+ steps=[1, 10, 100, 1000], value=10, label="Custom steps", show_value=True+ )+ vertical = mo.ui.slider(+ 0, 100, value=50, label="Vertical slider", orientation="vertical"+ )+ mo.vstack([slider, range_slider, custom_steps, vertical]).center()+ return custom_steps, range_slider, slider, vertical+++def __(mo):+ mo.md(r"""## Checkboxes and Radios""")+ return+++def __(mo):+ COLORS = ["red", "green", "blue"]+ colors = mo.ui.array(+ [mo.ui.checkbox(label=color) for color in COLORS],+ )++ shape = mo.ui.radio(+ ["circle", "square", "triangle"], inline=True, value="square"+ )+ mo.md(f"""+ Let's build something:++ **Pick a shape:**++ {shape}++ **Pick a color:**++ {colors.hstack().left()}+ """).center()+ return COLORS, colors, shape++[email protected](hide_code=True)+def __(COLORS, colors, mo, shape):+ selected_colors = [color for i, color in enumerate(COLORS) if colors.value[i]]+++ def draw_shape(shape, colors):+ if not colors:+ return ""++ gradient = ""+ if isinstance(colors, list) and len(colors) > 1:+ gradient_id = f"grad{hash(tuple(colors)) % 1000}"+ stops = "".join(+ [+ f'<stop offset="{i/(len(colors)-1)}" style="stop-color:{color};" />'+ for i, color in enumerate(colors)+ ]+ )+ gradient = f'<defs><linearGradient id="{gradient_id}" x1="0%" y1="0%" x2="100%" y2="100%">{stops}</linearGradient></defs>'+ fill_color = f"url(#{gradient_id})"+ else:+ fill_color = colors if isinstance(colors, str) else colors[0]++ if shape == "circle":+ html = f'<svg width="100" height="100">{gradient}<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="{fill_color}" /></svg>'+ elif shape == "square":+ html = f'<svg width="100" height="100">{gradient}<rect width="80" height="80" x="10" y="10" stroke="black" stroke-width="3" fill="{fill_color}" /></svg>'+ elif shape == "triangle":+ html = f'<svg width="100" height="100">{gradient}<polygon points="50,10 90,90 10,90" stroke="black" stroke-width="3" fill="{fill_color}" /></svg>'+ else:+ html = "Shape not recognized"+ return mo.Html(html)+++ mo.md(f"""+ A {"/".join(selected_colors)} {shape.value}:+ {draw_shape(shape.value, selected_colors)}+ """).center()+ return draw_shape, selected_colors+++def __(mo):+ mo.md("""## Dates""")+ return+++def __(mo):+ import datetime++ start_date = mo.ui.date(+ label="Start date",+ start=datetime.date(2020, 1, 1),+ stop=datetime.date(2020, 12, 31),+ )+ end_date = mo.ui.date(+ label="End date",+ start=datetime.date(2020, 1, 1),+ stop=datetime.date(2020, 12, 31),+ )+ mo.hstack([start_date, "➡️", end_date]).left()+ return datetime, end_date, start_date+++def __(mo):+ mo.md("""## Dropdowns""")+ return+++def __(mo):+ single = mo.ui.dropdown(+ ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5"],+ label="Single select",+ )+ multi = mo.ui.multiselect(+ ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5"],+ label="Multi select",+ value=["Option 1", "Option 2"],+ )+ mo.hstack([single, multi])+ return multi, single+++def __():+ import marimo as mo+ return mo,+++if __name__ == "__main__":+ app.run()diff --git a/examples/marimo/mermaid.py b/examples/marimo/mermaid.pyindex c7124cbea5..44bf8eeb31 100644--- a/examples/marimo/mermaid.py+++ b/examples/marimo/mermaid.py@@ -1,3 +1,9 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "marimo",+# ]+# ///import marimo__generated_with = "0.1.76"diff --git a/examples/marimo/refresh.py b/examples/marimo/refresh.pyindex 4e0df143b8..d6c03e92ae 100644--- a/examples/marimo/refresh.py+++ b/examples/marimo/refresh.py@@ -1,3 +1,13 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "pandas",+# "vega-datasets",+# "requests",+# "altair",+# "marimo",+# ]+# ///import marimo__generated_with = "0.1.68"diff --git a/examples/marimo/table.py b/examples/marimo/table.pyindex 6a2ed16f21..829806f139 100644--- a/examples/marimo/table.py+++ b/examples/marimo/table.py@@ -1,29 +1,38 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "marimo",+# ]+# ///+import marimo-__generated_with = "0.1.2"+__generated_with = "0.8.5"app = marimo.App()@app.celldef __(mo):- mo.md("""- # Tables+ mo.md(+ """+ # Tables- > “Sometimes I’ll start a sentence and I don’t even know where it’s going. I just hope I find it along the way.”- — Michael Scott- """)+ > “Sometimes I’ll start a sentence and I don’t even know where it’s going. I just hope I find it along the way.”+ — Michael Scott+ """+ )return@app.celldef __(mo):- mo.md("_Create rich tables with selectable rows using_ `mo.ui.table`.")+ mo.md("""_Create rich tables with selectable rows using_ `mo.ui.table`.""")return@app.celldef __(mo):- mo.md("**Single selection.**")+ mo.md("""**Single selection.**""")return@@ -45,7 +54,7 @@ def __(mo, single_select_table):@app.celldef __(mo):- mo.md("**Multi-selection.**")+ mo.md("""**Multi-selection.**""")return@@ -67,7 +76,7 @@ def __(mo, multi_select_table):@app.celldef __(mo):- mo.md("**No selection.**")+ mo.md("""**No selection.**""")returndiff --git a/examples/marimo/task_list.py b/examples/marimo/task_list.pyindex cc365f2faf..4755c019d8 100644--- a/examples/marimo/task_list.py+++ b/examples/marimo/task_list.py@@ -1,3 +1,9 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "marimo",+# ]+# ///import marimo__generated_with = "0.1.4"