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
example: histograms in duckdb (#2571)
Myles Scolnick1097be1cd5b0
diff --git a/examples/sql/README.md b/examples/sql/README.mdindex f4b34b4d1a..853ec78f6f 100644--- a/examples/sql/README.md+++ b/examples/sql/README.md@@ -12,6 +12,7 @@ analytical database.- `connect_to_sqlite.py` shows hows to connect to a SQLite database- `connect_to_postgres.py` shows hows to connect to a PostgreSQL database- `connect_to_motherduck.py` shows hows to connect to [motherduck](https://motherduck.com)+- `histograms.py` shows hows to plot histograms of a column's values- [`misc/`](misc/) contains illustrative examples> [!TIP]diff --git a/examples/sql/histograms.py b/examples/sql/histograms.pynew file mode 100644index 0000000000..19143bb517--- /dev/null+++ b/examples/sql/histograms.py@@ -0,0 +1,107 @@+# /// script+# requires-python = ">=3.12"+# dependencies = [+# "altair==5.4.1",+# "duckdb==1.1.1",+# "marimo",+# "openai==1.51.2",+# "polars==1.9.0",+# "pyarrow==17.0.0",+# ]+# ///++import marimo++__generated_with = "0.9.4"+app = marimo.App(width="medium")+++def __(mo):+ mo.md(+ r"""+ # SQL Histograms++ This notebook shows how to create a histogram of a column using built-in duckdb aggregate functions.+ """+ )+ return+++def __():+ import marimo as mo+ import duckdb+ import polars+ import pyarrow+ import altair as alt+ return alt, duckdb, mo, polars, pyarrow+++def __():+ URL = "hf://datasets/scikit-learn/Fish/Fish.csv"+ return (URL,)++[email protected](hide_code=True)+def __(URL, mo):+ mo.md(rf"""First we read the dataset at: **{URL}**""")+ return+++def __(URL, dataset, mo):+ dataset = mo.sql(+ f"""+ CREATE OR REPLACE VIEW dataset AS+ SELECT *+ FROM read_csv_auto('{URL}');+ FROM dataset+ """+ )+ return (dataset,)+++def __(dataset, mo):+ column = mo.ui.dropdown(+ dataset.columns, value=dataset.columns[0], label="Choose a column"+ )+ column+ return (column,)+++def __(column, mo):+ histogram = mo.sql(+ f"""+ -- Use the duckdb histogram function+ SELECT bin, count FROM histogram('dataset', {column.value}, bin_count := 10)+ """+ )+ return (histogram,)+++def __(mo):+ mo.md(r"""Now we will take the histogram result and plot it using [Altair](https://altair-viz.github.io/).""")+ return+++def __(alt, histogram):+ (+ alt.Chart(histogram)+ .mark_bar()+ .encode(+ x=alt.X("bin:N", sort=alt.EncodingSortField()).axis(labelAngle=20),+ y=alt.Y("count:Q"),+ )+ .properties(width="container")+ )+ return+++if __name__ == "__main__":+ app.run()