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: vegafusion background for mo.ui.altair_chart() (#7357)

Myles Scolnickce64ea98dc97
diff --git a/marimo/_data/series.py b/marimo/_data/series.py
index 7d3f2e86d0..9cca3cafba 100644
--- a/marimo/_data/series.py
+++ b/marimo/_data/series.py
@@ -48,14 +48,14 @@ class DateSeriesInfo:
label: str
-def _get_name(series: nw.Series) -> str:
+def _get_name(series: nw.Series[Any]) -> str:
if series.name is None:
return ""
return str(series.name)
@nw.narwhalify(eager_only=True, series_only=True)
-def get_number_series_info(series: nw.Series) -> NumberSeriesInfo:
+def get_number_series_info(series: nw.Series[Any]) -> NumberSeriesInfo:
"""
Get the summary of a numeric series.
"""
@@ -78,7 +78,7 @@ def get_number_series_info(series: nw.Series) -> NumberSeriesInfo:
@nw.narwhalify(eager_only=True, series_only=True)
-def get_category_series_info(series: nw.Series) -> CategorySeriesInfo:
+def get_category_series_info(series: nw.Series[Any]) -> CategorySeriesInfo:
"""
Get the summary of a categorical series.
"""
@@ -93,7 +93,7 @@ def get_category_series_info(series: nw.Series) -> CategorySeriesInfo:
@nw.narwhalify(eager_only=True, series_only=True)
-def get_date_series_info(series: nw.Series) -> DateSeriesInfo:
+def get_date_series_info(series: nw.Series[Any]) -> DateSeriesInfo:
"""
Get the summary of a date series.
"""
@@ -117,7 +117,7 @@ def get_date_series_info(series: nw.Series) -> DateSeriesInfo:
@nw.narwhalify(eager_only=True, series_only=True)
-def get_datetime_series_info(series: nw.Series) -> DateSeriesInfo:
+def get_datetime_series_info(series: nw.Series[Any]) -> DateSeriesInfo:
"""
Get the summary of a datetime series.
"""
diff --git a/marimo/_output/formatters/altair_formatters.py b/marimo/_output/formatters/altair_formatters.py
index c79e641c58..8db127b45c 100644
--- a/marimo/_output/formatters/altair_formatters.py
+++ b/marimo/_output/formatters/altair_formatters.py
@@ -13,6 +13,7 @@ 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 (
AltairChartType,
+ maybe_fix_vegafusion_background,
maybe_make_full_width,
)
from marimo._plugins.ui._impl.charts.altair_transformer import (
@@ -79,17 +80,10 @@ class AltairFormatter(FormatterFactory):
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
if alt.data_transformers.active.startswith("vegafusion"):
- # Bug https://github.com/marimo-team/marimo/issues/6601. Vegafusion defaults to white background
- # So, we set the background to transparent
- if (
- chart._get("background") is alt.Undefined # type: ignore
- ):
- LOGGER.debug("setting background to transparent")
- chart = chart.properties(background="transparent")
-
return (
"application/vnd.vega.v5+json",
chart_to_json(chart=chart, spec_format="vega"),
diff --git a/marimo/_plugins/ui/_impl/altair_chart.py b/marimo/_plugins/ui/_impl/altair_chart.py
index db8f1d1df6..15327511e1 100644
--- a/marimo/_plugins/ui/_impl/altair_chart.py
+++ b/marimo/_plugins/ui/_impl/altair_chart.py
@@ -446,6 +446,9 @@ class altair_chart(UIElement[ChartSelection, ChartDataType]):
# 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
@@ -752,6 +755,31 @@ def maybe_make_full_width(chart: AltairChartType) -> AltairChartType:
return chart
+def maybe_fix_vegafusion_background(chart: AltairChartType) -> AltairChartType:
+ """Fix vegafusion background to be transparent.
+
+ Vegafusion defaults to white background, which causes issues in dark mode.
+ See: https://github.com/marimo-team/marimo/issues/6601
+ """
+ import altair as alt
+
+ try:
+ if not _using_vegafusion():
+ return chart
+
+ # Only set background if it's not already set
+ if chart._get("background") is alt.Undefined: # type: ignore
+ LOGGER.debug("setting background to transparent for vegafusion")
+ return chart.properties(background="transparent")
+ return chart
+ except Exception:
+ LOGGER.exception(
+ "Failed to set vegafusion background to transparent. "
+ "Using chart as-is."
+ )
+ return chart
+
+
def _has_selection_param(chart: AltairChartType) -> bool:
import altair as alt
diff --git a/marimo/_utils/narwhals_utils.py b/marimo/_utils/narwhals_utils.py
index bb50cde775..a8b9cdfedb 100644
--- a/marimo/_utils/narwhals_utils.py
+++ b/marimo/_utils/narwhals_utils.py
@@ -51,7 +51,7 @@ def assert_narwhals_dataframe_or_lazyframe(
raise ValueError(f"Unsupported dataframe type. Got {type(df)}")
-def assert_narwhals_series(series: nw.Series) -> None:
+def assert_narwhals_series(series: nw.Series[Any]) -> None:
"""
Assert that the given series is a valid narwhals series.
"""
diff --git a/tests/_plugins/ui/_impl/test_altair_chart.py b/tests/_plugins/ui/_impl/test_altair_chart.py
index 6be77ef759..386f2431c2 100644
--- a/tests/_plugins/ui/_impl/test_altair_chart.py
+++ b/tests/_plugins/ui/_impl/test_altair_chart.py
@@ -25,7 +25,9 @@ from marimo._plugins.ui._impl.altair_chart import (
_has_selection_param,
_parse_spec,
_update_vconcat_width,
+ _using_vegafusion,
altair_chart,
+ maybe_fix_vegafusion_background,
)
from marimo._runtime.runtime import Kernel
from marimo._utils.narwhals_utils import is_narwhals_lazyframe
@@ -1733,3 +1735,102 @@ def test_embed_options_empty_dict() -> None:
# Clean up
del alt.renderers.options["embed_options"]
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_maybe_fix_vegafusion_background_not_using_vegafusion() -> None:
+ """Test that background is NOT changed when vegafusion is not active."""
+ import altair as alt
+
+ # Ensure vegafusion is not active
+ alt.data_transformers.enable("default")
+
+ data = pd.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})
+ chart = alt.Chart(data).mark_point().encode(x="x", y="y")
+
+ # Store original background
+ original_background = chart.background
+
+ # Apply the function
+ result_chart = maybe_fix_vegafusion_background(chart)
+
+ # Background should remain unchanged
+ assert result_chart.background == original_background
+ assert result_chart.background is alt.Undefined
+
+
+ not HAS_DEPS or not DependencyManager.vegafusion.has(),
+ reason="optional dependencies not installed",
+)
+def test_maybe_fix_vegafusion_background_with_vegafusion() -> None:
+ """Test that background is set to transparent when vegafusion is active."""
+ import altair as alt
+
+ # Enable vegafusion
+ alt.data_transformers.enable("vegafusion")
+
+ data = pd.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})
+ chart = alt.Chart(data).mark_point().encode(x="x", y="y")
+
+ # Verify background is undefined initially
+ assert chart.background is alt.Undefined
+
+ # Apply the function
+ result_chart = maybe_fix_vegafusion_background(chart)
+
+ # Background should be set to transparent
+ assert result_chart.background == "transparent"
+
+ # Clean up
+ alt.data_transformers.enable("default")
+
+
+ not HAS_DEPS or not DependencyManager.vegafusion.has(),
+ reason="optional dependencies not installed",
+)
+def test_maybe_fix_vegafusion_background_preserves_user_background() -> None:
+ """Test that user-set background is preserved even with vegafusion."""
+ import altair as alt
+
+ # Enable vegafusion
+ alt.data_transformers.enable("vegafusion")
+
+ data = pd.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})
+ chart = (
+ alt.Chart(data)
+ .mark_point()
+ .encode(x="x", y="y")
+ .properties(background="#ffffff")
+ )
+
+ # Verify background is set by user
+ assert chart.background == "#ffffff"
+
+ # Apply the function
+ result_chart = maybe_fix_vegafusion_background(chart)
+
+ # Background should remain as user set it
+ assert result_chart.background == "#ffffff"
+
+ # Clean up
+ alt.data_transformers.enable("default")
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_using_vegafusion() -> None:
+ """Test the _using_vegafusion helper function."""
+ import altair as alt
+
+ # Test with default transformer
+ alt.data_transformers.enable("default")
+ assert _using_vegafusion() is False
+
+ # Test with vegafusion (if available)
+ if DependencyManager.vegafusion.has():
+ alt.data_transformers.enable("vegafusion")
+ assert _using_vegafusion() is True
+
+ # Clean up
+ alt.data_transformers.enable("default")