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: grid dashboard (#2419)
Myles Scolnickbb2838f52d84
diff --git a/examples/layouts/grid-dashboard.py b/examples/layouts/grid-dashboard.pynew file mode 100644index 0000000000..20faf87955--- /dev/null+++ b/examples/layouts/grid-dashboard.py@@ -0,0 +1,428 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "altair==5.4.1",+# "hvplot==0.10.0",+# "marimo",+# "matplotlib==3.9.2",+# "numpy==2.1.1",+# "openai==1.49.0",+# "pandas==2.2.3",+# "panel==1.5.0",+# "plotly==5.24.1",+# ]+# ///++import marimo++__generated_with = "0.8.20"+app = marimo.App(+ width="medium",+ layout_file="layouts/grid-dashboard.grid.json",+)+++def __(mo):+ mo.md(r"""# Gapminder Dashboard""")+ return++[email protected](hide_code=True)+def __(__file__, mo):+ mo.md(+ rf"""+ !!! tip "This notebook is best viewed as an app."++ `marimo run {__file__}`++ or hit `Cmd/Ctrl+.` or click the "app view" button in the bottom right.+ """+ )+ return++[email protected](hide_code=True)+def __(mo):+ mo.md(+ """+ If you would like to see _how_ this application is made, continue down.++ This application is adapted from <https://examples.holoviz.org/gallery/gapminders/gapminders.html>+ """+ )+ return+++def __(mo):+ mo.md(r"""# Getting the data""")+ return+++def __():+ import numpy as np+ import pandas as pd+ import panel as pn+ import marimo as mo++ import altair as alt+ import plotly.graph_objs as go+ import plotly.io as pio+ import matplotlib.pyplot as plt+ import matplotlib as mpl+ import hvplot.pandas # noqa+ import warnings++ warnings.simplefilter("ignore")+ pn.extension("vega", "plotly", defer_load=True, sizing_mode="stretch_width")+ mpl.use("agg")+ return alt, go, hvplot, mo, mpl, np, pd, pio, plt, pn, warnings+++def __():+ XLABEL = "GDP per capita (2000 dollars)"+ YLABEL = "Life expectancy (years)"+ YLIM = (20, 90)+ HEIGHT = 500 # pixels+ WIDTH = 500 # pixels+ ACCENT = "#D397F8"+ PERIOD = 1000 # milliseconds+ return ACCENT, HEIGHT, PERIOD, WIDTH, XLABEL, YLABEL, YLIM+++def __(pd):+ dataset = pd.read_csv(+ "https://raw.githubusercontent.com/kirenz/datasets/b8f17b8fc4907748b3317554d65ffd780edcc057/gapminder.csv"+ )+ dataset.sample(5)+ return (dataset,)+++def __(dataset):+ YEARS = [int(year) for year in dataset.year.unique()]+ str(YEARS)+ return (YEARS,)+++def __(mo):+ mo.md(r"""# Charting the data""")+ return+++def __(dataset, np):+ # Common utility functions+++ def get_data(year):+ df = dataset[(dataset.year == year) & (dataset.gdpPercap < 10000)].copy()+ df["size"] = np.sqrt(df["pop"] * 2.666051223553066e-05)+ df["size_hvplot"] = df["size"] * 6+ return df+++ def get_title(library, year):+ return f"{library}: Life expectancy vs. GDP, {year}"+++ def get_xlim(data):+ return (+ dataset["gdpPercap"].min() - 100,+ dataset[dataset["gdpPercap"] < 10000].max()["gdpPercap"] + 1000,+ )+ return get_data, get_title, get_xlim+++def __(+ XLABEL,+ YLABEL,+ YLIM,+ alt,+ get_data,+ get_title,+ get_xlim,+ go,+ pio,+ plt,+):+ # Charting functions+++ def mpl_view(year=1952, show_legend=True):+ data = get_data(year)+ title = get_title("Matplotlib", year)+ xlim = get_xlim(data)++ plot = plt.figure(figsize=(10, 8), facecolor=(0, 0, 0, 0))+ ax = plot.add_subplot(111)+ ax.set_xscale("log")+ ax.set_title(title)+ ax.set_xlabel(XLABEL)+ ax.set_ylabel(YLABEL)+ ax.set_ylim(YLIM)+ ax.set_xlim(xlim)++ for continent, df in data.groupby("continent"):+ ax.scatter(+ df.gdpPercap,+ y=df.lifeExp,+ s=df["size"] * 5,+ edgecolor="black",+ label=continent,+ )++ if show_legend:+ ax.legend(loc=4)++ plt.close(plot)+ return plot+++ pio.templates.default = None+++ def plotly_view(year=1952, show_legend=True):+ data = get_data(year)+ title = get_title("Plotly", year)+ xlim = get_xlim(data)+ ylim = YLIM+ traces = []+ for continent, df in data.groupby("continent"):+ marker = dict(+ symbol="circle",+ sizemode="area",+ sizeref=0.1,+ size=df["size"],+ line=dict(width=2),+ )+ traces.append(+ go.Scatter(+ x=df.gdpPercap,+ y=df.lifeExp,+ mode="markers",+ marker=marker,+ name=continent,+ text=df.country,+ )+ )++ axis_opts = dict(+ gridcolor="rgb(255, 255, 255)", zerolinewidth=1, ticklen=5, gridwidth=2+ )+ layout = go.Layout(+ title=title,+ showlegend=show_legend,+ xaxis=dict(title=XLABEL, type="linear", range=xlim, **axis_opts),+ yaxis=dict(title=YLABEL, range=ylim, **axis_opts),+ autosize=True,+ paper_bgcolor="rgba(0,0,0,0)",+ )+ return go.Figure(data=traces, layout=layout)+++ def altair_view(+ year=1952, show_legend=True, height="container", width="container"+ ):+ data = get_data(year)+ title = get_title("Altair/ Vega", year)+ xlim = get_xlim(data)+ legend = {} if show_legend else {"legend": None}+ return (+ alt.Chart(data)+ .mark_circle()+ .encode(+ alt.X(+ "gdpPercap:Q",+ scale=alt.Scale(type="log", domain=xlim),+ axis=alt.Axis(title=XLABEL),+ ),+ alt.Y(+ "lifeExp:Q",+ scale=alt.Scale(zero=False, domain=YLIM),+ axis=alt.Axis(title=YLABEL),+ ),+ size=alt.Size("pop:Q", scale=alt.Scale(type="log"), legend=None),+ color=alt.Color(+ "continent", scale=alt.Scale(scheme="category10"), **legend+ ),+ tooltip=["continent", "country"],+ )+ .configure_axis(grid=False)+ .properties(+ title=title, height=height, width=width, background="rgba(0,0,0,0)"+ )+ .configure_view(fill="white")+ .interactive()+ )+++ def hvplot_view(year=1952, show_legend=True):+ data = get_data(year)+ title = get_title("hvPlot/ Bokeh", year)+ xlim = get_xlim(data)++ return data.hvplot.scatter(+ "gdpPercap",+ "lifeExp",+ by="continent",+ s="size_hvplot",+ alpha=0.8,+ logx=True,+ title=title,+ legend="bottom_right",+ hover_cols=["country"],+ ylim=YLIM,+ xlim=xlim,+ ylabel=YLABEL,+ xlabel=XLABEL,+ height=400,+ )+ return altair_view, hvplot_view, mpl_view, plotly_view+++def __(HEIGHT, altair_view, hvplot_view, mo, mpl_view, plotly_view):+ mo.ui.tabs(+ {+ "matplotlib": mpl_view(1952, True),+ "plotly": plotly_view(),+ "altair": altair_view(height=HEIGHT - 100),+ "hvplot": hvplot_view(),+ }+ )+ return+++def __(mo):+ mo.md(r"""# Building a dashboard""")+ return+++def __(mo):+ mo.md("""## Creating widgets""")+ return+++def __(YEARS, mo):+ get_year, set_year = mo.state(YEARS[-1])+ return get_year, set_year+++def __(YEARS, get_year, mo, set_year):+ year = mo.ui.slider(+ value=get_year(), steps=YEARS, full_width=True, on_change=set_year+ )+ show_legend = mo.ui.checkbox(value=True, label="Show Legend")+ return show_legend, year+++def __(mo, show_legend, year):+ mo.vstack(+ [+ mo.md(f"Year: **{year.value}**"),+ year,+ show_legend,+ ]+ )+ return+++def __(mo):+ autoplay = mo.ui.refresh(options=["1s", "3s", "5s"], label="Autoplay")+ autoplay+ return (autoplay,)+++def __(YEARS, autoplay, set_year):+ autoplay+++ def increment(v):+ if v is None:+ return YEARS[-1]+ index = (YEARS.index(v) + 1) % len(YEARS)+ return YEARS[index]+++ set_year(increment)+ return (increment,)+++def __(mo):+ mo.md(r"""## Creating the charts, reactive to the widgets""")+ return+++def __(mpl_view, show_legend, year):+ mpl_view(year=year.value, show_legend=show_legend.value)+ return+++def __(plotly_view, show_legend, year):+ plotly_view(year=year.value, show_legend=show_legend.value)+ return+++def __(HEIGHT, altair_view, show_legend, year):+ altair_view(year=year.value, show_legend=show_legend.value, height=HEIGHT - 100)+ return+++def __(hvplot_view, show_legend, year):+ hvplot_view(year=year.value, show_legend=show_legend.value)+ return++[email protected](hide_code=True)+def __(mo):+ mo.md(+ """+ ## Add any extra flair++ Next we will toggle to "App view" (hit `Cmd/Ctrl+.` or click the "app view") in order to layout our dashboard with the grid layout editor.+ """+ )+ return+++def __(mo):+ mo.image("https://marimo.io/logotype-wide.svg")+ return++[email protected](hide_code=True)+def __(mo):+ mo.md(+ """+ ## 🎓 Info++ Here you can try out four different plotting libraries controlled by a couple of widgets, for Hans Rosling's [gapminder](https://demo.bokeh.org/gapminder) example.++ This application is inspired by [Panel](https://examples.holoviz.org/gallery/gapminders/gapminders.html).+ """+ )+ return+++if __name__ == "__main__":+ app.run()diff --git a/examples/layouts/layouts/grid-dashboard.grid.json b/examples/layouts/layouts/grid-dashboard.grid.jsonnew file mode 100644index 0000000000..aa150236a9--- /dev/null+++ b/examples/layouts/layouts/grid-dashboard.grid.json@@ -0,0 +1,92 @@+{+ "type": "grid",+ "data": {+ "columns": 24,+ "rowHeight": 20,+ "maxWidth": 1400,+ "bordered": true,+ "cells": [+ {+ "position": [5, 0, 15, 3]+ },+ {+ "position": null+ },+ {+ "position": null+ },+ {+ "position": null+ },+ {+ "position": null+ },+ {+ "position": null+ },+ {+ "position": null+ },+ {+ "position": null+ },+ {+ "position": null+ },+ {+ "position": null+ },+ {+ "position": null+ },+ {+ "position": null+ },+ {+ "position": null+ },+ {+ "position": null+ },+ {+ "position": null+ },+ {+ "position": null+ },+ {+ "position": [0, 10, 5, 7]+ },+ {+ "position": [0, 7, 3, 3]+ },+ {+ "position": null+ },+ {+ "position": null+ },+ {+ "position": [5, 3, 9, 22]+ },+ {+ "position": [14, 3, 10, 22]+ },+ {+ "position": [5, 25, 9, 23]+ },+ {+ "position": [14, 25, 10, 23]+ },+ {+ "position": null+ },+ {+ "position": [0, 0, 5, 7]+ },+ {+ "position": [0, 17, 5, 28]+ }+ ]+ }+}diff --git a/pyproject.toml b/pyproject.tomlindex 2493be12c9..9665dbab02 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -313,6 +313,7 @@ omit = ["marimo/_tutorials/*"]wheres = "wheres"Ue = "Ue" # Used in one of the cell IDsNd = "Nd" # Confused with And+pn = "pn" # Panel[tool.typos.files]extend-exclude = [