Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion marimo/_plugins/ui/_impl/altair_chart.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,9 @@ def __init__(

register_transformers()

# Make a copy
original_chart = chart
chart = chart.copy()
self._chart = chart

if not isinstance(chart, (alt.TopLevelMixin)):
Expand All @@ -345,7 +348,14 @@ def __init__(
if chart.autosize is alt.Undefined:
chart.autosize = "fit-x"

vega_spec = _parse_spec(chart)
try:
vega_spec = _parse_spec(chart)
except Exception:
# Sometimes the changes to width and autosize (above) can cause `.to_dict()` to throw an error
# 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")
vega_spec = _parse_spec(original_chart)

if label:
vega_spec["title"] = label
Expand Down
50 changes: 50 additions & 0 deletions marimo/_smoke_tests/altair_examples/upset.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "altair-upset==0.4.0",
# "pandas==2.3.2",
# "pyarrow==22.0.0",
# ]
# ///

import marimo

__generated_with = "0.17.2"
app = marimo.App(width="medium", sql_output="polars")


@app.cell
def _():
import marimo as mo
import pandas as pd
import pyarrow
from altair_upset import UpSetAltair
return UpSetAltair, mo, pd


@app.cell
def _(pd):
df = pd.DataFrame({"a": [1, 1, 1, 1, 1, 0], "b": [1, 1, 1, 0, 0, 0]})
return (df,)


@app.cell
def _(UpSetAltair, df):
chart = UpSetAltair(df, sorted(df.columns)).chart
return (chart,)


@app.cell
def _(chart):
chart
return


@app.cell
def _(chart, mo):
mo.ui.altair_chart(chart.copy())
return


if __name__ == "__main__":
app.run()
17 changes: 17 additions & 0 deletions tests/_plugins/ui/_impl/test_altair_chart.py
Original file line number Diff line number Diff line change
Expand Up @@ -628,6 +628,23 @@ def test_does_not_modify_original() -> None:
assert combined1 == combined2._chart


@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
def test_creating_altair_chart_does_not_mutate_original() -> None:
import altair as alt

data = {"values": [1, 2, 3]}
original_chart = alt.Chart(data).mark_point().encode(x="values:Q")

# Store the original spec
original_spec = original_chart.to_dict()

# Create marimo altair_chart wrapper
_ = altair_chart(original_chart)

# Verify the original chart hasn't been mutated
assert original_chart.to_dict() == original_spec


@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
def test_get_dataframe() -> None:
import altair as alt
Expand Down
Loading