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
fix: vegafusion rendering when used outside mo.ui.altair_chart (#2285)
Myles Scolnick7a17a90d629f
diff --git a/marimo/_output/formatters/altair_formatters.py b/marimo/_output/formatters/altair_formatters.pyindex 22aa0b9ba2..574d805f27 100644--- a/marimo/_output/formatters/altair_formatters.py+++ b/marimo/_output/formatters/altair_formatters.py@@ -8,6 +8,7 @@ from marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output.builder import hfrom marimo._output.formatters.formatter_factory import FormatterFactoryfrom marimo._output.utils import flatten_string+from marimo._plugins.ui._impl.altair_chart import altair_chartclass AltairFormatter(FormatterFactory):@@ -30,6 +31,12 @@ class AltairFormatter(FormatterFactory):def _show_chart(chart: altair.Chart) -> tuple[KnownMimeType, str]:import altair as alt+ # If vegafusion is enabled, just wrap in altair_chart+ if alt.data_transformers.active.startswith("vegafusion"):+ return altair_chart(+ chart, chart_selection=False, legend_selection=False+ )._mime_()+# If the user has not set the max_rows option, we set it to 20_000# since we are able to handle the larger sizes (default is 5000)if "max_rows" not in alt.data_transformers.options:diff --git a/marimo/_plugins/ui/_impl/altair_chart.py b/marimo/_plugins/ui/_impl/altair_chart.pyindex 9dc6a851c2..3c989295b0 100644--- a/marimo/_plugins/ui/_impl/altair_chart.py+++ b/marimo/_plugins/ui/_impl/altair_chart.py@@ -262,7 +262,7 @@ def _parse_spec(spec: altair.TopLevelMixin) -> VegaSpec:# vegafusion requires creating a vega spec,# instead of using a vega-lite spec- if altair.data_transformers.active == "vegafusion":+ if altair.data_transformers.active.startswith("vegafusion"):return spec.to_dict(format="vega") # type: ignore# If this is a geoshape, use default transformer@@ -362,11 +362,7 @@ class altair_chart(UIElement[ChartSelection, ChartDataType]):)# Make full-width if no width is specified- if (- isinstance(chart, (alt.Chart, alt.LayerChart))- and chart.width is alt.Undefined- ):- chart = chart.properties(width="container")+ chart = maybe_make_full_width(chart)vega_spec = _parse_spec(chart)@@ -586,3 +582,21 @@ class altair_chart(UIElement[ChartSelection, ChartDataType]):def value(self, value: ChartDataType) -> None:del valueraise RuntimeError("Setting the value of a UIElement is not allowed.")+++def maybe_make_full_width(chart: altair.Chart) -> altair.Chart:+ import altair++ try:+ if (+ isinstance(chart, (altair.Chart, altair.LayerChart))+ and chart.width is altair.Undefined+ ):+ return chart.properties(width="container")+ return chart+ except Exception:+ LOGGER.exception(+ "Failed to set width to full container. "+ "This is likely due to a missing dependency or an invalid chart."+ )+ return chartdiff --git a/marimo/_smoke_tests/altair/vegafusion_nb.py b/marimo/_smoke_tests/altair/vegafusion_nb.pynew file mode 100644index 0000000000..07191bd847--- /dev/null+++ b/marimo/_smoke_tests/altair/vegafusion_nb.py@@ -0,0 +1,265 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "pandas",+# "altair",+# "marimo",+# "vegafusion",+# ]+# ///++import marimo++__generated_with = "0.8.14"+app = marimo.App(width="medium")+++def __():+ import marimo as mo+ return mo,+++def __(mo):+ mo.md(r"""# Basic examples""")+ return+++def __():+ import pandas as pd+ import altair as alt+ import vegafusion as vf++ # Comment out to disable duckdb connection+ vf.runtime.set_connection("duckdb")++ flights = pd.read_parquet(+ "https://vegafusion-datasets.s3.amazonaws.com/vega/flights_1m.parquet"+ )+ return alt, flights, pd, vf+++def __(alt, flights, mo):+ delay_hist = (+ alt.Chart(flights)+ .mark_bar()+ .encode(alt.X("delay", bin=alt.Bin(maxbins=30)), alt.Y("count()"))+ )++ with alt.data_transformers.enable("vegafusion"):+ mo.output.replace(delay_hist)+ return delay_hist,+++def __(alt, delay_hist):+ alt.data_transformers.enable("vegafusion")+ delay_hist+ return+++def __(alt, delay_hist, mo):+ alt.data_transformers.enable("vegafusion")+ mo.ui.altair_chart(delay_hist)+ return+++def __(alt, delay_hist, mo):+ # This should throw an error+ try:+ alt.data_transformers.enable("default")+ mo.output.replace(delay_hist)+ mo.output.replace("No error found")+ except Exception as e:+ print(e)+ return+++def __(mo):+ mo.md(+ r"""+ # Examples from vegafusion++ The examples below still hit `MARIMO_OUTPUT_MAX_BYTES` limitations, and require increasing this before running this notebook:++ ```+ export MARIMO_OUTPUT_MAX_BYTES=100_000_000+ ```+ """+ )+ return+++def __(mo):+ mo.md(r"""## Interactive Cross-filter""")+ return+++def __(alt):+ def make_cross_filter_chart(source):+ brush = alt.selection_interval(encodings=["x"])++ # Define the base chart, with the common parts of the+ # background and highlights+ base = (+ alt.Chart()+ .mark_bar()+ .encode(+ x=alt.X(+ alt.repeat("column"),+ type="quantitative",+ bin=alt.Bin(maxbins=20),+ ),+ y="count()",+ )+ .properties(width=160, height=130)+ )++ # gray background with selection+ background = base.encode(color=alt.value("#ddd")).add_params(brush)++ # blue highlights on the transformed data+ highlight = base.transform_filter(brush)++ # layer the two charts & repeat+ return (+ alt.layer(background, highlight, data=source)+ .transform_calculate("time", "hours(datum.date)")+ .repeat(column=["distance", "delay", "time"])+ )+ return make_cross_filter_chart,+++def __(alt, make_cross_filter_chart, pd):+ alt.data_transformers.enable("vegafusion")+ source_data = pd.read_parquet(+ "https://vegafusion-datasets.s3.amazonaws.com/vega/flights_200k.parquet"+ )+ make_cross_filter_chart(source_data)+ return source_data,+++def __(mo):+ mo.md(r"""## Interactive average""")+ return+++def __(alt):+ def make_average_chart(source):+ brush = alt.selection_interval(encodings=["x"])++ bars = (+ alt.Chart()+ .mark_bar()+ .encode(+ x="utcmonth(date):O",+ y="mean(precipitation):Q",+ opacity=alt.condition(+ brush, alt.OpacityValue(1), alt.OpacityValue(0.7)+ ),+ )+ .add_params(brush)+ )++ line = (+ alt.Chart()+ .mark_rule(color="firebrick")+ .encode(y="mean(precipitation):Q", size=alt.SizeValue(3))+ .transform_filter(brush)+ )++ return alt.layer(bars, line, data=source).properties(height=200)+ return make_average_chart,+++def __(alt, make_average_chart, pd):+ alt.data_transformers.enable("vegafusion")+ _source_data = pd.read_parquet(+ "https://vegafusion-datasets.s3.amazonaws.com/vega/seattle_weather_200k.parquet"+ )+ make_average_chart(_source_data)+ return+++def __(mo):+ mo.md(r"""## Interactive Chart with Cross-Highlight""")+ return+++def __(alt):+ def make_movie_chart(data_source):+ pts = alt.selection_point(encodings=["x"])++ rect = (+ alt.Chart(data_source)+ .mark_rect()+ .encode(+ alt.X("IMDB_Rating:Q", bin=True),+ alt.Y("Rotten_Tomatoes_Rating:Q", bin=True),+ alt.Color(+ "count()",+ scale=alt.Scale(scheme="greenblue"),+ legend=alt.Legend(title="Total Records"),+ ),+ )+ )++ circ = (+ rect.mark_point()+ .encode(+ alt.ColorValue("grey"),+ alt.Size(+ "count()", legend=alt.Legend(title="Records in Selection")+ ),+ )+ .transform_filter(pts)+ .properties(width=300, height=250)+ )++ bar = (+ alt.Chart(data_source)+ .mark_bar()+ .encode(+ x="Major_Genre:N",+ y="count()",+ color=alt.condition(+ pts, alt.ColorValue("steelblue"), alt.ColorValue("grey")+ ),+ )+ .properties(width=300, height=250)+ .add_params(pts)+ )++ return alt.hconcat(+ bar,+ rect + circ,+ ).resolve_legend(color="independent", size="independent")+ return make_movie_chart,+++def __(alt, make_movie_chart, pd):+ alt.data_transformers.enable("vegafusion")+ _source_data = pd.read_parquet(+ "https://vegafusion-datasets.s3.amazonaws.com/vega/movies_201k.parquet"+ )+ make_movie_chart(_source_data)+ return+++if __name__ == "__main__":+ app.run()