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.

Remove default container width for altair charts (#8696)

Shahmir Varqhaff9110de2331
diff --git a/frontend/src/plugins/impl/data-explorer/ConnectedDataExplorerComponent.tsx b/frontend/src/plugins/impl/data-explorer/ConnectedDataExplorerComponent.tsx
index 077f64eb06..87653963ca 100644
--- a/frontend/src/plugins/impl/data-explorer/ConnectedDataExplorerComponent.tsx
+++ b/frontend/src/plugins/impl/data-explorer/ConnectedDataExplorerComponent.tsx
@@ -13,6 +13,7 @@ import { Tooltip } from "@/components/ui/tooltip";
import { useAsyncData } from "@/hooks/useAsyncData";
import { useOnMount } from "@/hooks/useLifecycle";
import { type ResolvedTheme, useTheme } from "@/theme/useTheme";
+import { cn } from "@/utils/cn";
import { Objects } from "@/utils/objects";
import { ErrorBanner } from "../common/error-banner";
import { vegaLoadData } from "../vega/loader";
@@ -139,9 +140,15 @@ export const DataExplorerComponent = ({
const responsiveSpec = makeResponsive(spec);
// TODO: We can optimize by updating the data dynamically. https://github.com/vega/react-vega?tab=readme-ov-file#recipes
const augmentedSpec = augmentSpecWithData(responsiveSpec, chartData);
+ const isContainerWidth = responsiveSpec.width === "container";
return (
- <div className="flex overflow-y-auto justify-center items-center flex-1 w-[90%]">
+ <div
+ className={cn(
+ "flex overflow-y-auto justify-center items-center flex-1 w-[90%]",
+ isContainerWidth && "vega-container-width",
+ )}
+ >
<VegaEmbed spec={augmentedSpec} options={chartOptions(theme)} />
</div>
);
diff --git a/frontend/src/plugins/impl/vega/vega-component.tsx b/frontend/src/plugins/impl/vega/vega-component.tsx
index 8641af0bdb..a4827e2d3f 100644
--- a/frontend/src/plugins/impl/vega/vega-component.tsx
+++ b/frontend/src/plugins/impl/vega/vega-component.tsx
@@ -16,6 +16,7 @@ import { Tooltip } from "@/components/ui/tooltip";
import { useAsyncData } from "@/hooks/useAsyncData";
import { useDeepCompareMemoize } from "@/hooks/useDeepCompareMemoize";
import { useTheme } from "@/theme/useTheme";
+import { cn } from "@/utils/cn";
import { Events } from "@/utils/events";
import { Logger } from "@/utils/Logger";
import { Objects } from "@/utils/objects";
@@ -304,7 +305,12 @@ const LoadedVegaComponent = ({
</Alert>
)}
<div
- className="relative"
+ className={cn(
+ "relative",
+ "width" in selectableSpec &&
+ selectableSpec.width === "container" &&
+ "vega-container-width",
+ )}
// Capture the pointer down event to prevent the parent from handling it
onPointerDown={Events.stopPropagation()}
>
diff --git a/frontend/src/plugins/impl/vega/vega.css b/frontend/src/plugins/impl/vega/vega.css
index f22eed232e..e4c66deb5c 100644
--- a/frontend/src/plugins/impl/vega/vega.css
+++ b/frontend/src/plugins/impl/vega/vega.css
@@ -1,18 +1,11 @@
@reference "../../../css/globals.css";
.vega-embed {
- width: 100%;
- flex: 1;
- display: inline-block;
-
- @media (min-width: 500px) {
- min-width: 300px;
- }
+ max-width: 100%;
+}
- /* For vega embeds in slots, reset the styles to let the user set the width */
- @container style(--slot: true) {
- min-width: unset;
- }
+.vega-container-width .vega-embed {
+ width: 100%;
}
.vega-embed > .chart-wrapper {
diff --git a/marimo/_output/formatters/altair_formatters.py b/marimo/_output/formatters/altair_formatters.py
index b75ed3dc63..287acfab1f 100644
--- a/marimo/_output/formatters/altair_formatters.py
+++ b/marimo/_output/formatters/altair_formatters.py
@@ -17,7 +17,6 @@ from marimo._plugins.ui._impl.altair_chart import (
chart_to_json,
get_chart_mimetype,
maybe_fix_vegafusion_background,
- maybe_make_full_width,
)
from marimo._utils.data_uri import build_data_url
@@ -85,7 +84,6 @@ class AltairFormatter(FormatterFactory):
return mime_type, json.dumps(mime_response)
chart = _apply_embed_options(chart)
- chart = maybe_make_full_width(chart)
chart = maybe_fix_vegafusion_background(chart)
# If vegafusion is enabled, just wrap in altair_chart
diff --git a/marimo/_plugins/ui/_impl/altair_chart.py b/marimo/_plugins/ui/_impl/altair_chart.py
index 008b953b1d..cb18c2627e 100644
--- a/marimo/_plugins/ui/_impl/altair_chart.py
+++ b/marimo/_plugins/ui/_impl/altair_chart.py
@@ -548,26 +548,13 @@ class altair_chart(UIElement[ChartSelection, ChartDataType]):
f"Invalid type for chart: {type(chart)}; expected altair.Chart"
)
- # Make full-width if no width is specified
- chart = maybe_make_full_width(chart)
-
# Fix vegafusion background to be transparent
chart = maybe_fix_vegafusion_background(chart)
- # Fix the sizing for vconcat charts
- if isinstance(chart, alt.VConcatChart) and _has_no_nested_hconcat(
- chart
- ):
- chart = _update_vconcat_width(chart)
-
- # without autosize, vconcat will overflow
- if chart.autosize is alt.Undefined:
- chart.autosize = "fit-x"
-
try:
vega_spec = _parse_spec(chart)
except Exception:
- # Sometimes the changes to width and autosize (above) can cause `.to_dict()` to throw an error
+ # Parsing the chart spec (via Altair's `.to_dict()`) can fail for some charts,
# similarly to the issue described in https://github.com/marimo-team/marimo/issues/6244
# so we fallback to the original chart.
LOGGER.info("Failed to parse spec, using original chart")
@@ -670,7 +657,7 @@ class altair_chart(UIElement[ChartSelection, ChartDataType]):
@staticmethod
def _get_dataframe_from_chart(
- chart: Union[altair.Chart, altair.LayerChart],
+ chart: AltairChartType,
) -> Optional[ChartDataType]:
if not isinstance(chart.data, str):
return cast(ChartDataType, chart.data)
@@ -844,31 +831,6 @@ class altair_chart(UIElement[ChartSelection, ChartDataType]):
raise RuntimeError("Setting the value of a UIElement is not allowed.")
-def maybe_make_full_width(chart: AltairChartType) -> AltairChartType:
- import altair as alt
-
- try:
- if (
- isinstance(chart, (alt.Chart, alt.LayerChart))
- and chart.width is alt.Undefined
- ):
- # Don't make full width if chart has column encoding (faceted)
- if (
- hasattr(chart, "encoding")
- and hasattr(chart.encoding, "column")
- and chart.encoding.column is not alt.Undefined
- ):
- return chart
- 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 chart
-
-
def maybe_fix_vegafusion_background(chart: AltairChartType) -> AltairChartType:
"""Fix vegafusion background to be transparent.
@@ -938,49 +900,6 @@ def _has_legend_param(chart: AltairChartType) -> bool:
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
-
-
-def _has_no_nested_hconcat(chart: AltairChartType) -> bool:
- import altair as alt
-
- if isinstance(chart, alt.HConcatChart):
- return False
- if isinstance(chart, alt.VConcatChart):
- return all(
- _has_no_nested_hconcat(subchart) for subchart in chart.vconcat
- )
- if isinstance(chart, alt.LayerChart):
- return all(_has_no_nested_hconcat(layer) for layer in chart.layer)
-
- return True
-
-
def chart_to_json(
chart: AltairChartType,
spec_format: Literal["vega", "vega-lite"] = "vega-lite",
diff --git a/tests/_output/formatters/test_altair_formatters.py b/tests/_output/formatters/test_altair_formatters.py
index db550ced49..0302697935 100644
--- a/tests/_output/formatters/test_altair_formatters.py
+++ b/tests/_output/formatters/test_altair_formatters.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import json
from datetime import datetime
from typing import TYPE_CHECKING
-from unittest.mock import MagicMock, patch
+from unittest.mock import patch
from urllib.request import urlopen
import pytest
@@ -16,7 +16,6 @@ from marimo._output.formatters.altair_formatters import (
)
from marimo._output.formatters.formatters import register_formatters
from marimo._output.formatting import get_formatter
-from marimo._plugins.ui._impl.altair_chart import maybe_make_full_width
from tests._data.mocks import create_dataframes
HAS_DEPS = DependencyManager.altair.has() and DependencyManager.polars.has()
@@ -83,12 +82,9 @@ def test_altair_formatter_registration():
@pytest.mark.skipif(not HAS_DEPS, reason="altair not installed")
-@patch("marimo._output.formatters.altair_formatters.maybe_make_full_width")
-def test_altair_formatter_full_width(mock_make_full_width: MagicMock):
+def test_altair_formatter_respects_default_width():
AltairFormatter().register()
- mock_make_full_width.side_effect = maybe_make_full_width
-
import altair as alt
cars = get_data()
@@ -101,8 +97,6 @@ def test_altair_formatter_full_width(mock_make_full_width: MagicMock):
)
)
- mock_make_full_width.return_value = chart
-
formatter = get_formatter(chart)
assert formatter is not None
res = formatter(chart)
@@ -110,10 +104,8 @@ def test_altair_formatter_full_width(mock_make_full_width: MagicMock):
mime, content = res
assert_vegalite_mimetype(mime)
assert isinstance(content, str)
- assert "container" in content
-
- # Verify maybe_make_full_width was called
- mock_make_full_width.assert_called_once()
+ json_content = json.loads(content)
+ assert json_content.get("width") != "container"
@pytest.mark.skipif(not HAS_DEPS, reason="altair not installed")
diff --git a/tests/_plugins/ui/_impl/test_altair_chart.py b/tests/_plugins/ui/_impl/test_altair_chart.py
index 8349e9f591..cf80d89170 100644
--- a/tests/_plugins/ui/_impl/test_altair_chart.py
+++ b/tests/_plugins/ui/_impl/test_altair_chart.py
@@ -21,10 +21,8 @@ from marimo._plugins.ui._impl.altair_chart import (
_has_binning,
_has_geoshape,
_has_legend_param,
- _has_no_nested_hconcat,
_has_selection_param,
_parse_spec,
- _update_vconcat_width,
_using_vegafusion,
altair_chart,
maybe_fix_vegafusion_background,
@@ -1556,167 +1554,30 @@ def test_has_legend_param() -> None:
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
-def test_update_vconcat_width() -> None:
+def test_autosize_not_applied_by_default() -> 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"
-
-
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
-def test_chart_with_column_encoding_not_full_width() -> None:
- import altair as alt
-
- from marimo._plugins.ui._impl.altair_chart import maybe_make_full_width
-
- # Create a chart with column encoding (faceted chart)
- data = pd.DataFrame(
- {
- "x": [1, 2, 3, 4],
- "y": [4, 5, 6, 7],
- "category": ["A", "B", "A", "B"],
- }
- )
- chart = (
- alt.Chart(data)
- .mark_point()
- .encode(x="x:Q", y="y:Q", column="category:N")
- )
-
- # Test that chart with column encoding is NOT made full width
- result = maybe_make_full_width(chart)
- assert result.width is alt.Undefined
-
- # Test that chart without column encoding IS made full width
- chart_without_column = (
- alt.Chart(data).mark_point().encode(x="x:Q", y="y:Q")
- )
- result_without_column = maybe_make_full_width(chart_without_column)
- assert result_without_column.width == "container"
-
-
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
-def test_has_no_nested_hconcat() -> None:
- import altair as alt
-
- # Create simple charts
- 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()
-
- # Simple chart has no hconcat
- assert _has_no_nested_hconcat(chart1) is True
-
- # HConcatChart should return False
- hconcat_chart = alt.hconcat(chart1, chart2)
- assert _has_no_nested_hconcat(hconcat_chart) is False
-
- # VConcatChart with no nested hconcat should return True
- vconcat_chart = alt.vconcat(chart1, chart2)
- assert _has_no_nested_hconcat(vconcat_chart) is True
-
- # LayerChart with no nested hconcat should return True
- layer_chart = alt.layer(chart1, chart2)
- assert _has_no_nested_hconcat(layer_chart) is True
-
- # VConcatChart with nested HConcatChart should return False
- nested_vconcat_with_hconcat = alt.vconcat(hconcat_chart, chart1)
- assert _has_no_nested_hconcat(nested_vconcat_with_hconcat) is False
-
- # VConcatChart with nested VConcatChart (no hconcat) should return True
- nested_vconcat = alt.vconcat(
- alt.vconcat(chart1, chart2), alt.vconcat(chart1, chart2)
- )
- assert _has_no_nested_hconcat(nested_vconcat) is True
-
- # LayerChart with simple charts (no hconcat) should return True
- layer_simple = alt.layer(chart1, chart2)
- assert _has_no_nested_hconcat(layer_simple) is True
-
- # VConcatChart with nested layers (no hconcat) should return True
- vconcat_with_layer = alt.vconcat(chart1, alt.layer(chart1, chart2))
- assert _has_no_nested_hconcat(vconcat_with_layer) is True
-
- # Deeply nested VConcat with HConcat should return False
- deeply_nested = alt.vconcat(alt.vconcat(chart1, hconcat_chart), chart2)
- assert _has_no_nested_hconcat(deeply_nested) is False
-
-
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
-def test_autosize_not_applied_with_nested_hconcat() -> None:
- import altair as alt
-
- # Create simple charts
data = pd.DataFrame({"x": [1, 2], "y": [3, 4]})
chart1 = alt.Chart(data).mark_point().encode(x="x", y="y")
chart2 = alt.Chart(data).mark_line().encode(x="x", y="y")
- def get_autosize(chart: dict[str, Any]) -> str | None:
- return chart.get("autosize")
+ def get_autosize(spec: dict[str, Any]) -> str | None:
+ return spec.get("autosize")
+
+ simple_vconcat = alt.vconcat(chart1, chart2)
+ marimo_chart_simple = altair_chart(simple_vconcat)
+ assert get_autosize(marimo_chart_simple._spec) is None
- # Test 1: VConcatChart with nested HConcatChart should NOT have autosize applied
hconcat_chart = alt.hconcat(chart1, chart2)
vconcat_with_hconcat = alt.vconcat(hconcat_chart, chart1)
-
marimo_chart = altair_chart(vconcat_with_hconcat)
- # The autosize should remain Undefined (not set to "fit-x")
assert get_autosize(marimo_chart._spec) is None
- # Test 2: Simple VConcatChart (no nested hconcat) SHOULD have autosize applied
- simple_vconcat = alt.vconcat(chart1, chart2)
- marimo_chart_simple = altair_chart(simple_vconcat)
- # The autosize should be set to "fit-x"
- assert get_autosize(marimo_chart_simple._spec) == "fit-x"
-
- # Test 3: VConcatChart with nested vconcat containing hconcat should NOT have autosize
- nested_with_hconcat = alt.vconcat(
- alt.vconcat(chart1, hconcat_chart), chart2
- )
-
- marimo_chart_complex = altair_chart(nested_with_hconcat)
- assert get_autosize(marimo_chart_complex._spec) is None
-
- # Test 4: VConcatChart with explicit autosize should not be overridden
+ # Explicit autosize set by the user should be preserved
vconcat_with_autosize = alt.vconcat(chart1, chart2).properties(
autosize="none"
)
marimo_chart_explicit = altair_chart(vconcat_with_autosize)
- # Should keep the explicit autosize value
assert get_autosize(marimo_chart_explicit._spec) == "none"