Skip to content

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.

fix: set width on nested vconcat charts (#5020)

Myles Scolnick6e26332d2f08
diff --git a/marimo/_output/formatters/altair_formatters.py b/marimo/_output/formatters/altair_formatters.py
index 4636f22df5..9a976c3da2 100644
--- a/marimo/_output/formatters/altair_formatters.py
+++ b/marimo/_output/formatters/altair_formatters.py
@@ -2,20 +2,20 @@
from __future__ import annotations
import json
-from typing import TYPE_CHECKING, Literal, Union
+from typing import Literal
from marimo._config.config import Theme
from marimo._messaging.mimetypes import KnownMimeType, MimeBundleOrTuple
from marimo._output.formatters.formatter_factory import FormatterFactory
from marimo._plugins.core.media import io_to_data_url
-from marimo._plugins.ui._impl.altair_chart import maybe_make_full_width
+from marimo._plugins.ui._impl.altair_chart import (
+ AltairChartType,
+ maybe_make_full_width,
+)
from marimo._plugins.ui._impl.charts.altair_transformer import (
sanitize_nan_infs,
)
-if TYPE_CHECKING:
- import altair
-
class AltairFormatter(FormatterFactory):
@staticmethod
@@ -34,9 +34,7 @@ class AltairFormatter(FormatterFactory):
register_transformers()
@formatting.formatter(altair.TopLevelMixin)
- def _show_chart(
- chart: Union[altair.Chart, altair.LayerChart],
- ) -> tuple[KnownMimeType, str]:
+ def _show_chart(chart: AltairChartType) -> tuple[KnownMimeType, str]:
import altair as alt
# Try to get the _repr_mimebundle_ method from the chart
@@ -106,9 +104,7 @@ class AltairFormatter(FormatterFactory):
# This is only needed since it seems that altair does not
# handle this internally.
# https://github.com/marimo-team/marimo/issues/2302
-def _apply_embed_options(
- chart: Union[altair.Chart, altair.LayerChart],
-) -> Union[altair.Chart, altair.LayerChart]:
+def _apply_embed_options(chart: AltairChartType) -> AltairChartType:
import altair as alt
# Respect user-set embed options
@@ -128,7 +124,7 @@ def _apply_embed_options(
def chart_to_json(
- chart: Union[altair.Chart, altair.LayerChart],
+ chart: AltairChartType,
spec_format: Literal["vega", "vega-lite"] = "vega-lite",
validate: bool = True,
) -> str:
diff --git a/marimo/_plugins/ui/_impl/altair_chart.py b/marimo/_plugins/ui/_impl/altair_chart.py
index c0d94dac33..25e9b7d890 100644
--- a/marimo/_plugins/ui/_impl/altair_chart.py
+++ b/marimo/_plugins/ui/_impl/altair_chart.py
@@ -31,10 +31,16 @@ from marimo._utils.narwhals_utils import (
empty_df,
)
+if sys.version_info < (3, 10):
+ from typing_extensions import TypeAlias
+else:
+ from typing import TypeAlias
+
LOGGER = _loggers.marimo_logger()
if TYPE_CHECKING:
import altair
+ import altair.vegalite
# Selection is a dictionary of the form:
# {
@@ -50,6 +56,9 @@ ColumnOrientedData = dict[str, list[Any]]
ChartDataType = Union[IntoDataFrame, RowOrientedData, ColumnOrientedData]
+# Union of all possible chart types
+AltairChartType: TypeAlias = "altair.vegalite.v5.api.ChartType"
+
def _has_binning(spec: VegaSpec) -> bool:
"""Return True if the spec has binning."""
@@ -214,20 +223,20 @@ def _is_numeric_or_date(value: Any) -> bool:
def _parse_spec(spec: altair.TopLevelMixin) -> VegaSpec:
- import altair
+ import altair as alt
# vegafusion requires creating a vega spec,
# instead of using a vega-lite spec
- if altair.data_transformers.active.startswith("vegafusion"):
+ if alt.data_transformers.active.startswith("vegafusion"):
return spec.to_dict(format="vega") # type: ignore
# If this is a geoshape, use default transformer
# since ours does not support geoshapes
if _has_geoshape(spec):
- with altair.data_transformers.enable("default"):
+ with alt.data_transformers.enable("default"):
return spec.to_dict() # type: ignore
- with altair.data_transformers.enable("marimo_arrow"):
+ with alt.data_transformers.enable("marimo_arrow"):
return spec.to_dict(validate=False) # type: ignore
@@ -294,7 +303,7 @@ class altair_chart(UIElement[ChartSelection, ChartDataType]):
def __init__(
self,
- chart: Union[altair.Chart, altair.LayerChart],
+ chart: AltairChartType,
chart_selection: Literal["point"] | Literal["interval"] | bool = True,
legend_selection: list[str] | bool = True,
*,
@@ -317,20 +326,19 @@ class altair_chart(UIElement[ChartSelection, ChartDataType]):
# Make full-width if no width is specified
chart = maybe_make_full_width(chart)
+ # Fix the sizing for vconcat charts
+ if isinstance(chart, alt.VConcatChart):
+ chart = _update_vconcat_width(chart)
+
+ # without autosize, vconcat will overflow
+ if chart.autosize is alt.Undefined:
+ chart.autosize = "fit-x"
+
vega_spec = _parse_spec(chart)
if label:
vega_spec["title"] = label
- # Fix the sizing for vconcat charts
- if "vconcat" in vega_spec:
- for subchart in vega_spec["vconcat"]:
- if "width" not in subchart:
- subchart["width"] = "container"
- # without autosize, vconcat will overflow
- if "autosize" not in vega_spec:
- vega_spec["autosize"] = "fit-x"
-
# Types say this is not possible,
# but a user still may pass none
if chart_selection is None: # type: ignore
@@ -349,6 +357,7 @@ class altair_chart(UIElement[ChartSelection, ChartDataType]):
f"Ignoring chart_selection={chart_selection}"
)
chart_selection = False
+
if _has_legend_param(chart):
# Log a warning if the user has set legend_selection
# but the chart already has a legend param
@@ -447,9 +456,9 @@ class altair_chart(UIElement[ChartSelection, ChartDataType]):
if url.endswith(".json"):
return pd.read_json(url)
- import altair
+ import altair as alt
- if chart.data is altair.Undefined: # type: ignore[comparison-overlap]
+ if chart.data is alt.Undefined: # type: ignore[comparison-overlap]
return None
return cast(ChartDataType, chart.data)
@@ -578,15 +587,13 @@ class altair_chart(UIElement[ChartSelection, ChartDataType]):
raise RuntimeError("Setting the value of a UIElement is not allowed.")
-def maybe_make_full_width(
- chart: Union[altair.Chart, altair.LayerChart],
-) -> Union[altair.Chart, altair.LayerChart]:
- import altair
+def maybe_make_full_width(chart: AltairChartType) -> AltairChartType:
+ import altair as alt
try:
if (
- isinstance(chart, (altair.Chart, altair.LayerChart))
- and chart.width is altair.Undefined
+ isinstance(chart, (alt.Chart, alt.LayerChart))
+ and chart.width is alt.Undefined
):
return chart.properties(width="container")
return chart
@@ -598,9 +605,7 @@ def maybe_make_full_width(
return chart
-def _has_selection_param(
- chart: Union[altair.Chart, altair.LayerChart],
-) -> bool:
+def _has_selection_param(chart: AltairChartType) -> bool:
import altair as alt
if not hasattr(chart, "params"):
@@ -622,9 +627,7 @@ def _has_selection_param(
return False
-def _has_legend_param(
- chart: Union[altair.Chart, altair.LayerChart],
-) -> bool:
+def _has_legend_param(chart: AltairChartType) -> bool:
import altair as alt
if not hasattr(chart, "params"):
@@ -644,3 +647,31 @@ def _has_legend_param(
except Exception:
pass
return False
+
+
+def _update_vconcat_width(chart: AltairChartType) -> AltairChartType:
+ """Mutate the chart to set the width to the container."""
+
+ import altair as alt
+
+ if isinstance(chart, alt.VConcatChart):
+ chart.vconcat = [
+ _update_vconcat_width(subchart) for subchart in chart.vconcat
+ ]
+ return chart # type: ignore[no-any-return]
+
+ if isinstance(chart, alt.LayerChart):
+ chart.layer = [_update_vconcat_width(layer) for layer in chart.layer]
+ return chart # type: ignore[no-any-return]
+
+ if isinstance(chart, alt.HConcatChart):
+ chart.hconcat = [
+ _update_vconcat_width(subchart) for subchart in chart.hconcat
+ ]
+ return chart # type: ignore[no-any-return]
+
+ if isinstance(chart, alt.Chart):
+ return maybe_make_full_width(chart)
+
+ # Not handled
+ return chart
diff --git a/marimo/_smoke_tests/altair/nested_vconcat.py b/marimo/_smoke_tests/altair/nested_vconcat.py
new file mode 100644
index 0000000000..2f63925815
--- /dev/null
+++ b/marimo/_smoke_tests/altair/nested_vconcat.py
@@ -0,0 +1,43 @@
+import marimo
+
+__generated_with = "0.13.11"
+app = marimo.App(width="medium")
+
+
+def _():
+ from vega_datasets import data
+ import marimo as mo
+ import altair as alt
+
+ cars = data.cars()
+
+ _chart = (
+ alt.Chart(cars)
+ .mark_point()
+ .encode(
+ x="Horsepower",
+ y="Miles_per_Gallon",
+ color="Origin",
+ )
+ .properties(height=100)
+ )
+
+ stacked_chart = alt.vconcat(
+ _chart,
+ alt.vconcat(_chart, alt.vconcat(_chart, _chart)),
+ )
+
+
+ mo.ui.altair_chart(stacked_chart)
+ return (stacked_chart,)
+
+
+def _(stacked_chart):
+ stacked_chart
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_plugins/ui/_impl/test_altair_chart.py b/tests/_plugins/ui/_impl/test_altair_chart.py
index e044e38816..49ee40fa22 100644
--- a/tests/_plugins/ui/_impl/test_altair_chart.py
+++ b/tests/_plugins/ui/_impl/test_altair_chart.py
@@ -20,6 +20,7 @@ from marimo._plugins.ui._impl.altair_chart import (
_has_legend_param,
_has_selection_param,
_parse_spec,
+ _update_vconcat_width,
altair_chart,
)
from marimo._runtime.runtime import Kernel
@@ -980,3 +981,47 @@ def test_has_legend_param() -> None:
# Invalid chart
chart = None
assert _has_legend_param(chart) is False
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_update_vconcat_width() -> None:
+ import altair as alt
+
+ # Create a simple chart
+ chart1 = alt.Chart(pd.DataFrame({"x": [1, 2], "y": [3, 4]})).mark_point()
+ chart2 = alt.Chart(pd.DataFrame({"x": [1, 2], "y": [3, 4]})).mark_line()
+
+ # Create a vconcat chart
+ vconcat_chart = alt.vconcat(chart1, chart2)
+
+ # Update the width
+ updated_chart = _update_vconcat_width(vconcat_chart)
+
+ # Check that the width is set to container for both subcharts
+ assert updated_chart.vconcat[0].width == "container"
+ assert updated_chart.vconcat[1].width == "container"
+
+ # Test with nested vconcat
+ nested_vconcat = alt.vconcat(
+ alt.vconcat(chart1, chart2), alt.vconcat(chart1, chart2)
+ )
+
+ updated_nested = _update_vconcat_width(nested_vconcat)
+
+ # Check that all nested charts have container width
+ assert updated_nested.vconcat[0].vconcat[0].width == "container"
+ assert updated_nested.vconcat[0].vconcat[1].width == "container"
+ assert updated_nested.vconcat[1].vconcat[0].width == "container"
+ assert updated_nested.vconcat[1].vconcat[1].width == "container"
+
+ # Test with layer chart
+ layer_chart = alt.layer(chart1, chart2)
+ updated_layer = _update_vconcat_width(layer_chart)
+ assert updated_layer.layer[0].width == "container"
+ assert updated_layer.layer[1].width == "container"
+
+ # Test with hconcat chart
+ hconcat_chart = alt.hconcat(chart1, chart2)
+ updated_hconcat = _update_vconcat_width(hconcat_chart)
+ assert updated_hconcat.hconcat[0].width == "container"
+ assert updated_hconcat.hconcat[1].width == "container"