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
improvement: Custom altair data_transformer, load 1 million points (#200)
Myles Scolnick3293c1315b1e
diff --git a/frontend/src/plugins/impl/vega/VegaPlugin.tsx b/frontend/src/plugins/impl/vega/VegaPlugin.tsxindex a16715eaa7..47e17a76ef 100644--- a/frontend/src/plugins/impl/vega/VegaPlugin.tsx+++ b/frontend/src/plugins/impl/vega/VegaPlugin.tsx@@ -13,6 +13,7 @@ import { useDebugMounting, usePropsDidChange } from "@/hooks/debug";import { debounce } from "lodash-es";import useEvent from "react-use-event-hook";import { Logger } from "@/utils/Logger";+import { fixRelativeUrl } from "./fix-relative-url";import "./vega.css";@@ -88,7 +89,10 @@ export const VegaComponent = ({// Aggressively memoize the spec, so Vega doesn't re-render/re-mount the componentconst selectableSpec = useMemo(() => {- return makeSelectable(spec, { chartSelection, fieldSelection });+ return makeSelectable(fixRelativeUrl(spec), {+ chartSelection,+ fieldSelection,+ });// eslint-disable-next-line react-hooks/exhaustive-deps}, [useDeepCompareMemoize(spec), chartSelection, fieldSelection]);const names = useMemo(diff --git a/frontend/src/plugins/impl/vega/fix-relative-url.ts b/frontend/src/plugins/impl/vega/fix-relative-url.tsnew file mode 100644index 0000000000..b4c7ab9b99--- /dev/null+++ b/frontend/src/plugins/impl/vega/fix-relative-url.ts@@ -0,0 +1,14 @@+/* Copyright 2023 Marimo. All rights reserved. */++import { VegaLiteSpec } from "./types";++/**+ * If the URL in the data-spec if relative, we need to fix it to be absolute,+ * otherwise vega-lite throws an error.+ */+export function fixRelativeUrl(spec: VegaLiteSpec) {+ if (spec.data && "url" in spec.data && spec.data.url.startsWith("/")) {+ spec.data.url = `${window.location.origin}${spec.data.url}`;+ }+ return spec;+}diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.pynew file mode 100644index 0000000000..ca9e194c0b--- /dev/null+++ b/marimo/_dependencies/dependencies.py@@ -0,0 +1,48 @@+# Copyright 2023 Marimo. All rights reserved.+from __future__ import annotations++import importlib.util+++class DependencyManager:+ """Utilities for checking the status of dependencies."""++ @staticmethod+ def require_pandas(why: str) -> None:+ """+ Raise an ModuleNotFoundError if pandas is not installed.++ Args:+ why: A string of the form "for <reason>" that will be appended++ """+ if not DependencyManager.has_pandas():+ raise ModuleNotFoundError(+ f"pandas is required {why}. "+ + "You can install it with 'pip install pandas'"+ ) from None++ @staticmethod+ def require_altair(why: str) -> None:+ """+ Raise an ModuleNotFoundError if altair is not installed.++ Args:+ why: A string of the form "for <reason>" that will be appended++ """+ if not DependencyManager.has_altair():+ raise ModuleNotFoundError(+ f"altair is required {why}. "+ + "You can install it with 'pip install altair'"+ ) from None++ @staticmethod+ def has_pandas() -> bool:+ """Return True if pandas is installed."""+ return importlib.util.find_spec("pandas") is not None++ @staticmethod+ def has_altair() -> bool:+ """Return True if altair is installed."""+ return importlib.util.find_spec("altair") is not Nonediff --git a/marimo/_output/data/data.py b/marimo/_output/data/data.pyindex 33240b8238..a00c34db55 100644--- a/marimo/_output/data/data.py+++ b/marimo/_output/data/data.py@@ -1,11 +1,10 @@# Copyright 2023 Marimo. All rights reserved.import base64import io-from typing import Union+from typing import TYPE_CHECKING, Union-from marimo._plugins.core.media import (- is_data_empty,-)+from marimo._dependencies.dependencies import DependencyManager+from marimo._plugins.core.media import is_data_emptyfrom marimo._runtime.context import get_contextfrom marimo._runtime.virtual_file import (EMPTY_VIRTUAL_FILE,@@ -13,6 +12,9 @@ from marimo._runtime.virtual_file import (VirtualFileLifecycleItem,)+if TYPE_CHECKING:+ import pandas as pd+def pdf(data: bytes) -> VirtualFile:"""Create a virtual file from a PDF.@@ -46,6 +48,54 @@ def image(data: bytes, ext: str = "png") -> VirtualFile:return item.virtual_file+def csv(data: Union[str, bytes, io.BytesIO, "pd.DataFrame"]) -> VirtualFile:+ """Create a virtual file for CSV data.++ **Args.**++ - data: CSV data in bytes, or string representing a data URL, external URL+ or a Pandas DataFrame++ **Returns.**++ A `VirtualFile` object.+ """+ # Pandas DataFrame+ if DependencyManager.has_pandas():+ import pandas as pd++ if isinstance(data, pd.DataFrame):+ buffer = data.to_csv(+ index=False,+ ).encode("utf-8")+ return any_data(buffer, ext="csv")++ return any_data(data, ext="csv") # type: ignore+++def json(data: Union[str, bytes, io.BytesIO, "pd.DataFrame"]) -> VirtualFile:+ """Create a virtual file for JSON data.++ **Args.**++ - data: JSON data in bytes, or string representing a data URL, external URL+ or a Pandas DataFrame++ **Returns.**++ A `VirtualFile` object.+ """+ # Pandas DataFrame+ if DependencyManager.has_pandas():+ import pandas as pd++ if isinstance(data, pd.DataFrame):+ buffer = data.to_json(orient="records").encode("utf-8")+ return any_data(buffer, ext="json")++ return any_data(data, ext="json") # type: ignore++def any_data(data: Union[str, bytes, io.BytesIO], ext: str) -> VirtualFile:"""Create a virtual file from any data.@@ -77,7 +127,7 @@ def any_data(data: Union[str, bytes, io.BytesIO], ext: str) -> VirtualFile:# URLif isinstance(data, str):- return VirtualFile(url=data, filename=data, buffer=b"")+ return VirtualFile.from_external_url(data)# Bytesif isinstance(data, bytes):diff --git a/marimo/_output/formatters/altair_formatters.py b/marimo/_output/formatters/altair_formatters.pyindex df453e0171..5776a65e90 100644--- a/marimo/_output/formatters/altair_formatters.py+++ b/marimo/_output/formatters/altair_formatters.py@@ -23,6 +23,13 @@ class AltairFormatter(FormatterFactory):# resizing entirely in the frontend# `__resizeIframe` is a script defined in the frontend that sets# the height of the iframe to the height of the contained document+ import altair as alt++ # It is required to set this back to the default,+ # since mo.ui.altair_chart sets it to 'marimo'+ # We also change the max_rows to 20_000 (default is 5000)+ # since we are able to handle the larger sizes+ alt.data_transformers.enable("default", max_rows=20_000)return ("text/html",(diff --git a/marimo/_plugins/ui/_impl/altair_chart.py b/marimo/_plugins/ui/_impl/altair_chart.pyindex 5869b9e1e1..815342ee9a 100644--- a/marimo/_plugins/ui/_impl/altair_chart.py+++ b/marimo/_plugins/ui/_impl/altair_chart.py@@ -1,7 +1,6 @@# Copyright 2023 Marimo. All rights reserved.from __future__ import annotations-import jsonimport sysfrom typing import (TYPE_CHECKING,@@ -16,8 +15,12 @@ from typing import ()from marimo import _loggers+from marimo._dependencies.dependencies import DependencyManagerfrom marimo._output.rich_help import mddocfrom marimo._plugins.ui._core.ui_element import UIElement+from marimo._plugins.ui._impl.charts.altair_transformer import (+ register_transformers,+)from marimo._utils import flattenLOGGER = _loggers.marimo_logger()@@ -46,49 +49,11 @@ def _has_binning(spec: VegaSpec) -> bool:return False-def _to_dataframe(vega_spec: VegaSpec) -> pd.DataFrame:- # Try to import pandas- try:- import pandas as pd- except ImportError:- LOGGER.error("Pandas is required to render Vega-Lite charts")- raise ImportError(- "Pandas is required to render Vega-Lite charts"- ) from None-- data = vega_spec.get("data", {})- if "url" in data:- # If the data is defined as a URL,- # use pandas to read the data from the URL- if data["url"].endswith(".csv"):- df = pd.read_csv(data["url"])- elif data["url"].endswith(".json"):- df = pd.read_json(data["url"])- else:- raise ValueError(- f'Unsupported data format: {data["url"]}'- ) from None- elif "values" in data:- # If the data is defined as an inline list,- # convert the list to a DataFrame- df = pd.DataFrame(data["values"])- elif "name" in data:- # If the data is defined as a named data source,- # try to find the data source in the Vega-Lite spec- name = data["name"]- datasets = vega_spec.get("datasets", {})- if name in datasets:- df = pd.DataFrame(datasets[name])- else:- raise ValueError(f"Could not find data source {name}") from None- else:- raise ValueError("Data source not supported") from None- return df--def _filter_dataframe(- df: pd.DataFrame, selection: ChartSelection+ df_prev: pd.DataFrame, selection: ChartSelection) -> pd.DataFrame:+ # Make a copy of the DataFrame+ df = df_prev.copy()for _channel, fields in selection.items():# If vlPoint is in the selection,# then the selection is a point selection@@ -117,28 +82,14 @@ def _filter_dataframe(return df-def _parse_spec(spec: Union[str, altair.Chart, VegaSpec]) -> VegaSpec:- if spec is None or spec == "":- return {}-- # Parse Altair chart, str, or dict- try:- try:- import altair-- if isinstance(spec, altair.Chart):- return json.loads(spec.to_json()) # type: ignore- except ImportError:- pass-- if isinstance(spec, dict):- return spec- elif isinstance(spec, str):- return json.loads(spec) # type: ignore- except json.JSONDecodeError as err:- raise ValueError(f"Invalid Vega-Lite spec: {spec}") from err+def _parse_spec(spec: altair.TopLevelMixin) -> VegaSpec:+ import altair- raise ValueError("Invalid Vega-Lite spec") from None+ # vegafusion requires creating a vega spec,+ # instead of using a vega-lite spec+ if altair.data_transformers.active == "vegafusion":+ return spec.to_dict(format="vega") # type: ignore+ return spec.to_dict() # type: ignore@mddoc@@ -193,22 +144,35 @@ class altair_chart(UIElement[ChartSelection, "pd.DataFrame"]):def __init__(self,- figure: altair.Chart,+ chart: altair.Chart,chart_selection: Literal["point"] | Literal["interval"] | bool = True,legend_selection: list[str] | bool = True,*,label: str = "",on_change: Optional[Callable[[pd.DataFrame], None]] = None,) -> None:- vega_spec = _parse_spec(figure)- self.dataframe = _to_dataframe(vega_spec)+ DependencyManager.require_altair(why="to use `mo.ui.altair_chart`")++ import altair as alt++ # TODO: is this the right place to register the transformers?+ register_transformers()++ if not isinstance(chart, (alt.TopLevelMixin)):+ raise ValueError(+ "Invalid type for chart: "+ f"{type(chart)}; expected altair.Chart"+ )++ if isinstance(chart, (alt.Chart, alt.LayerChart)):+ chart = chart.properties(width="container")++ vega_spec = _parse_spec(chart)if label:vega_spec["title"] = label- # Automatically add full width- if "width" not in vega_spec:- vega_spec["width"] = "container"+ # Fix the sizing for vconcat chartsif "vconcat" in vega_spec:for chart in vega_spec["vconcat"]:if "width" not in chart:@@ -228,6 +192,8 @@ class altair_chart(UIElement[ChartSelection, "pd.DataFrame"]):chart_selection = Falselegend_selection = False+ self.dataframe = chart.data+super().__init__(component_name="marimo-vega",initial_value={},diff --git a/marimo/_plugins/ui/_impl/charts/altair_transformer.py b/marimo/_plugins/ui/_impl/charts/altair_transformer.pynew file mode 100644index 0000000000..a06c56d366--- /dev/null+++ b/marimo/_plugins/ui/_impl/charts/altair_transformer.py@@ -0,0 +1,117 @@+# Copyright 2023 Marimo. All rights reserved.+import json+from typing import TYPE_CHECKING, Literal, TypedDict, Union++import marimo._output.data.data as mo_data++if TYPE_CHECKING:+ import pandas as pd++Data = Union[dict, "pd.DataFrame"]+_DataType = Union[dict, "pd.DataFrame"]+++class _JsonFormatDict(TypedDict):+ type: Literal["json"]+++class _CsvFormatDict(TypedDict):+ type: Literal["csv"]+++class _ToJsonReturnUrlDict(TypedDict):+ url: str+ format: _JsonFormatDict+++class _ToCsvReturnUrlDict(TypedDict):+ url: str+ format: _CsvFormatDict+++def _to_marimo_json(data: Data) -> _ToJsonReturnUrlDict:+ """+ Custom implementation of altair.utils.data.to_json that+ returns a VirtualFile URL instead of writing to disk.+ """+ data_json = _data_to_json_string(data)+ virtual_file = mo_data.json(data_json.encode("utf-8"))+ return {"url": virtual_file.url, "format": {"type": "json"}}+++def _to_marimo_csv(data: Data) -> _ToCsvReturnUrlDict:+ """+ Custom implementation of altair.utils.data.to_csv that+ returns a VirtualFile URL instead of writing to disk.+ """+ data_csv = _data_to_csv_string(data)+ virtual_file = mo_data.csv(data_csv.encode("utf-8"))+ return {"url": virtual_file.url, "format": {"type": "csv"}}+++# Copied from https://github.com/altair-viz/altair/blob/0ca83784e2455f2b84d0f6d789af2abbe8814348/altair/utils/data.py#L263C1-L288C10+def _data_to_json_string(data: _DataType) -> str:+ """Return a JSON string representation of the input data"""+ import altair as alt # type: ignore[import]+ import pandas as pd++ if isinstance(data, pd.DataFrame):+ sanitized = alt.utils.sanitize_dataframe(data)+ as_str = sanitized.to_json(orient="records", double_precision=15)+ assert isinstance(as_str, str)+ return as_str+ elif isinstance(data, dict):+ if "values" not in data:+ raise KeyError("values expected in data dict, but not present.")+ return json.dumps(data["values"], sort_keys=True)+ else:+ raise NotImplementedError(+ "to_marimo_json only works with data expressed as a DataFrame "+ + " or as a dict"+ )+++def _data_to_csv_string(data: _DataType) -> str:+ """Return a CSV string representation of the input data"""+ import altair as alt+ import pandas as pd++ if isinstance(data, pd.DataFrame):+ sanitized = alt.utils.sanitize_dataframe(data)+ as_str = sanitized.to_csv(index=False)+ assert isinstance(as_str, str)+ return as_str+ elif isinstance(data, dict):+ if "values" not in data:+ raise KeyError("values expected in data dict, but not present")+ return pd.DataFrame.from_dict(data["values"]).to_csv(index=False)+ else:+ raise NotImplementedError(+ "to_marimo_csv only works with data expressed as a DataFrame"+ + " or as a dict"+ )+++def register_transformers() -> None:+ """+ Register custom data transformers for Altair.++ We register a CSV transformer and a JSON transformer. These+ transformers return a VirtualFile URL instead of writing to disk,+ which is the default behavior of Altair's to_csv and to_json.++ By registering these transformers, we are able to use+ much larger datasets.+ """+ import altair as alt++ # Default to CSV. Due to the columnar nature of CSV, it is more efficient+ # than JSON for large datasets (~80% smaller file size).+ alt.data_transformers.register("marimo", _to_marimo_csv)+ alt.data_transformers.enable("marimo")++ alt.data_transformers.register("marimo_json", _to_marimo_json)+ alt.data_transformers.register(+ "marimo_csv",+ _to_marimo_csv,+ )diff --git a/marimo/_plugins/ui/_impl/test_altair_chart.py b/marimo/_plugins/ui/_impl/test_altair_chart.pyindex 44bec2133c..2f6eb88a13 100644--- a/marimo/_plugins/ui/_impl/test_altair_chart.py+++ b/marimo/_plugins/ui/_impl/test_altair_chart.py@@ -5,63 +5,10 @@ import pandas as pdfrom marimo._plugins.ui._impl.altair_chart import (ChartSelection,- VegaSpec,_filter_dataframe,- _to_dataframe,)-def test_to_data_frame() -> None:- # Test with URL data source- vega_spec_url: VegaSpec = {- "data": {- "url": "https://raw.githubusercontent.com/vega/vega/main/docs/data/cars.json"- }- }- df_url = _to_dataframe(vega_spec_url)- assert isinstance(df_url, pd.DataFrame)- assert not df_url.empty-- # Test with inline list data source- vega_spec_values: VegaSpec = {- "data": {- "values": [- {"column1": "value1", "column2": "value2"},- {"column1": "value3", "column2": "value4"},- ]- }- }- df_values = _to_dataframe(vega_spec_values)- assert isinstance(df_values, pd.DataFrame)- assert not df_values.empty- assert len(df_values) == 2- assert list(df_values.columns) == ["column1", "column2"]-- # Test with named data source- vega_spec_values = {- "data": {"name": "named_data_source"},- "datasets": {- "named_data_source": [- {"column1": "value1", "column2": "value2"},- {"column1": "value3", "column2": "value4"},- ]- },- }- df_values = _to_dataframe(vega_spec_values)- assert isinstance(df_values, pd.DataFrame)- assert not df_values.empty- assert len(df_values) == 2- assert list(df_values.columns) == ["column1", "column2"]-- # Test with unsupported data source- vega_spec_unsupported = {"data": {"name": "named_data_source"}}- try:- _to_dataframe(vega_spec_unsupported)- raise AssertionError("Expected ValueError was not raised")- except ValueError:- pass--def test_filter_dataframe() -> None:df = pd.DataFrame({diff --git a/marimo/_runtime/virtual_file.py b/marimo/_runtime/virtual_file.pyindex 889868b52c..7c11d74d46 100644--- a/marimo/_runtime/virtual_file.py+++ b/marimo/_runtime/virtual_file.py@@ -34,15 +34,28 @@ class VirtualFile:filename: strbuffer: bytes- def __init__(self, filename: str, url: str, buffer: bytes) -> None:+ def __init__(+ self, filename: str, buffer: bytes, url: Optional[str] = None+ ) -> None:self.filename = filename- self.url = urlself.buffer = buffer+ # Create a file URL with the buffer size+ # This is a hack so when we pull from shared memory we know how+ # many bytes to read.+ self.url = url or f"/@file/{len(buffer)}-{filename}"++ @staticmethod+ def from_external_url(url: str) -> VirtualFile:+ return VirtualFile(+ filename=url,+ buffer=b"",+ url=url,+ )EMPTY_VIRTUAL_FILE = VirtualFile(filename="empty.txt",- url="/@file/empty.txt",+ url="/@file/0-empty.txt",buffer=b"",)@@ -73,9 +86,7 @@ class VirtualFileLifecycleItem(CellLifecycleItem):"Failed to add virtual file to registry. ""This is a bug in marimo. Please file an issue.")- self._virtual_file = VirtualFile(- filename, f"/@file/{filename}", self.buffer- )+ self._virtual_file = VirtualFile(filename, self.buffer)context.virtual_file_registry.add(self._virtual_file)def dispose(self, context: "RuntimeContext") -> None:diff --git a/marimo/_server/api/virtual_file.py b/marimo/_server/api/virtual_file.pyindex deabe90e29..d6eebc3423 100644--- a/marimo/_server/api/virtual_file.py+++ b/marimo/_server/api/virtual_file.py@@ -18,11 +18,12 @@ LOGGER = _loggers.marimo_logger()class VirtualFileHandler(tornado.web.RequestHandler):"""Handler for virtual files."""- def get(self, filename: str) -> None:- if filename == EMPTY_VIRTUAL_FILE.filename:+ def get(self, filename_and_length: str) -> None:+ if filename_and_length == EMPTY_VIRTUAL_FILE.filename:self.write(b"")return+ byte_length, filename = filename_and_length.split("-", 1)key = filenameshm = Nonetry:@@ -30,7 +31,7 @@ class VirtualFileHandler(tornado.web.RequestHandler):# doing it in one line yields a 'released memoryview ...'# because shared_memory has built in ref-tracking + GCshm = shared_memory.SharedMemory(name=key)- buffer_contents = bytes(shm.buf)+ buffer_contents = bytes(shm.buf)[: int(byte_length)]except FileNotFoundError as err:raise tornado.web.HTTPError(HTTPStatus.NOT_FOUND,diff --git a/marimo/_smoke_tests/charts/1mil_flights.py b/marimo/_smoke_tests/charts/1mil_flights.pynew file mode 100644index 0000000000..ae32198fed--- /dev/null+++ b/marimo/_smoke_tests/charts/1mil_flights.py@@ -0,0 +1,208 @@+import marimo++__generated_with = "0.1.24"+app = marimo.App(width="full")+++def __(pd):+ # Load some large data+ all_flights = pd.read_parquet(+ "https://vegafusion-datasets.s3.amazonaws.com/vega/flights_1m.parquet"+ )+ return all_flights,+++def __(mo):+ size = mo.ui.radio(+ label="Size",+ options=["100", "1000", "10000", "100000", "1000000"],+ value="100000",+ )+ size+ return size,+++def __(all_flights, size):+ flights = all_flights.sample(int(size.value))+ return flights,+++def __(flights):+ f"{len(flights):,} flights"+ return+++def __(alt, mo, pd):+ # List available data transformers+ mo.ui.altair_chart(alt.Chart(pd.DataFrame({"a": [1]})).mark_point())+ mo.accordion(+ {+ "Debug": mo.md(+ f"""+ Available data transformers: **{", ".join(alt.data_transformers.names())}**++ Current data transformer: **{alt.data_transformers.active}**+ """+ )+ }+ )+ return+++def __(alt, flights, mo):+ flight_histogram = mo.ui.altair_chart(+ alt.Chart(flights).mark_bar().encode(alt.X("delay"), alt.Y("count()"))+ )+ flight_histogram+ return flight_histogram,+++def __(flight_histogram, mo):+ mo.stop(len(flight_histogram.value) == 0, None)++ mo.md(f"Selected **{len(flight_histogram.value):,}** flights")+ return+++def __(alt, flight_histogram, mo):+ mo.stop(len(flight_histogram.value) == 0, None)++ origin_chart = mo.ui.altair_chart(+ alt.Chart(flight_histogram.value)+ .mark_bar()+ .encode(alt.X("origin:O"), alt.Y("count()"))+ )+ destination_chart = mo.ui.altair_chart(+ alt.Chart(flight_histogram.value)+ .mark_bar()+ .encode(alt.X("destination:O"), alt.Y("count()"))+ )+ mo.hstack([origin_chart, destination_chart])+ return destination_chart, origin_chart+++def __(airports, alt, data, flight_histogram, mo):+ flights_airport = flight_histogram.value+ # flights_airport = data.flights_airport.url++ states = alt.topo_feature(data.us_10m.url, feature="states")++ # Create mouseover selection+ select_city = alt.selection_point(+ on="mouseover", nearest=True, fields=["origin"], empty=False+ )++ # Define which attributes to lookup from airports.csv+ lookup_data = alt.LookupData(+ airports, key="iata", fields=["state", "latitude", "longitude"]+ )++ background = (+ alt.Chart(states)+ .mark_geoshape(fill="lightgray", stroke="white")+ .properties(width=750, height=500)+ .project("albersUsa")+ )++ connections = (+ alt.Chart(flights_airport)+ .mark_rule(opacity=0.5, strokeWidth=0.04)+ .encode(+ latitude="latitude:Q",+ longitude="longitude:Q",+ latitude2="lat2:Q",+ longitude2="lon2:Q",+ )+ .transform_lookup(lookup="origin", from_=lookup_data)+ .transform_lookup(+ lookup="destination", from_=lookup_data, as_=["state", "lat2", "lon2"]+ )+ .transform_filter(select_city)+ )++ points = (+ alt.Chart(flights_airport)+ .mark_circle()+ .encode(+ latitude="latitude:Q",+ longitude="longitude:Q",+ size=alt.Size("routes:Q").legend(None).scale(range=[0, 1000]),+ order=alt.Order("routes:Q").sort("descending"),+ tooltip=["origin:N", "routes:Q"],+ )+ .transform_aggregate(routes="count()", groupby=["origin"])+ .transform_lookup(lookup="origin", from_=lookup_data)+ .transform_filter((alt.datum.state != "PR") & (alt.datum.state != "VI"))+ .add_params(select_city)+ )++ mo.ui.altair_chart(+ (background + connections + points).configure_view(stroke=None)+ )+ return (+ background,+ connections,+ flights_airport,+ lookup_data,+ points,+ select_city,+ states,+ )+++def __(flight_histogram, mo):+ mo.stop(len(flight_histogram.value) == 0, None)++ mo.hstack(+ [+ mo.md(+ f"Top airport: **{flight_histogram.value['origin'].value_counts().index[0]}**"+ ),+ flight_histogram.value.describe(),+ # mo.ui.table(+ # flight_histogram.value.to_dict(orient="records"), pagination=False+ # ),+ ]+ )+ return++[email protected](disabled=True)+def __(alt, brush, flights, mo):+ # Run the same chart with vegafusion+ with alt.data_transformers.enable("vegafusion"):+ million_histogram = (+ alt.Chart(flights)+ .mark_bar()+ .encode(alt.X("delay"), alt.Y("count()"))+ .add_params(brush)+ )+ mo.output.append(mo.ui.altair_chart(million_histogram))+ return million_histogram,+++def __():+ import marimo as mo+ import pandas as pd+ import altair as alt+ from vega_datasets import data++ airports = data.airports.url++ None+ return airports, alt, data, mo, pd+++if __name__ == "__main__":+ app.run()