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
Add support for initial chart properties in `data_explorer` (#5028)
Janosh Riebesell70eb160921a8
diff --git a/docs/api/inputs/data_explorer.md b/docs/api/inputs/data_explorer.mdindex d9f79624d5..f670f43151 100644--- a/docs/api/inputs/data_explorer.md+++ b/docs/api/inputs/data_explorer.md@@ -24,4 +24,29 @@ def __():///+To set an initial configuration, you can pass keyword arguments to `mo.ui.data_explorer`. For example, to start with `sepal_length` on the x-axis, `sepal_width` on the y-axis, and `species` as the color encoding:++/// marimo-embed+ size: large+ app_width: full++```python+def __():+ import marimo as mo+ import pandas as pd+ import pyodide+ csv = pyodide.http.open_url("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv")+ df = pd.read_csv(csv)+ mo.ui.data_explorer(+ df,+ x="sepal_length",+ y="sepal_width",+ color="species",+ )+ return+```++///+::: marimo.ui.data_explorerdiff --git a/marimo/_plugins/ui/_impl/data_explorer.py b/marimo/_plugins/ui/_impl/data_explorer.pyindex fd510543f3..900fe67584 100644--- a/marimo/_plugins/ui/_impl/data_explorer.py+++ b/marimo/_plugins/ui/_impl/data_explorer.py@@ -20,15 +20,24 @@ class data_explorer(UIElement[dict[str, Any], dict[str, Any]]):Examples:```pythonmo.ui.data_explorer(data)+ mo.ui.data_explorer(data, x="col_A", y="col_B", color="col_C")```Attributes:- value (Dict[str, Any]): The resulting DataFrame chart spec.+ value (Dict[str, Any]): The chart specification, which may include+ initial selections if provided via keyword arguments.Args:df (IntoDataFrame): The DataFrame to visualize.- on_change (Callable[[dict[str, object]], None], optional): Optional callback+ on_change (Callable[[dict[str, Any]], None], optional): Optional callbackto run when this element's value changes.+ x (Optional[str]): Initial column for the x-axis. Defaults to None.+ y (Optional[str]): Initial column for the y-axis. Defaults to None.+ row (Optional[str]): Initial column for the row dimension. Defaults to None.+ column (Optional[str]): Initial column for the column dimension. Defaults to None.+ color (Optional[str]): Initial column for the color encoding. Defaults to None.+ size (Optional[str]): Initial column for the size encoding. Defaults to None.+ shape (Optional[str]): Initial column for the shape encoding. Defaults to None."""_name: Final[str] = "marimo-data-explorer"@@ -37,16 +46,31 @@ class data_explorer(UIElement[dict[str, Any], dict[str, Any]]):self,df: IntoDataFrame,on_change: Optional[Callable[[dict[str, Any]], None]] = None,+ x: Optional[str] = None,+ y: Optional[str] = None,+ row: Optional[str] = None,+ column: Optional[str] = None,+ color: Optional[str] = None,+ size: Optional[str] = None,+ shape: Optional[str] = None,) -> None:# Drop the index since empty column names break the data explorer- df = _drop_index(df)- self._data = df+ df_no_idx = _drop_index(df)+ self._data = df_no_idx- manager = get_table_manager(df)+ manager = get_table_manager(df_no_idx)super().__init__(component_name=data_explorer._name,- initial_value={},+ initial_value={+ "x": x,+ "y": y,+ "row": row,+ "column": column,+ "color": color,+ "size": size,+ "shape": shape,+ },on_change=on_change,label="",args={diff --git a/tests/_plugins/ui/_impl/test_data_explorer.py b/tests/_plugins/ui/_impl/test_data_explorer.pyindex a2a1fb8470..d24560e1f2 100644--- a/tests/_plugins/ui/_impl/test_data_explorer.py+++ b/tests/_plugins/ui/_impl/test_data_explorer.py@@ -2,6 +2,7 @@from __future__ import annotationsfrom typing import Any+from unittest.mock import Mockimport pytest@@ -14,6 +15,12 @@ from tests._data.mocks import create_dataframesHAS_DEPS = DependencyManager.pandas.has()+if HAS_DEPS:+ import pandas as pd+else:+ pd = Mock()++@pytest.mark.parametrize("df",create_dataframes({"A": [1, 2, 3], "B": [4, 5, 6]}, exclude=["duckdb"]),@@ -28,8 +35,6 @@ def test_data_explorer(df: Any) -> None:reason="optional dependencies not installed or windows",)def test_data_explorer_index() -> None:- import pandas as pd-# With indexdf = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}, index=["a", "b", "c"])explorer = data_explorer.data_explorer(df)@@ -47,3 +52,39 @@ def test_data_explorer_index() -> None:explorer = data_explorer.data_explorer(df)data = explorer._component_args["data"]assert from_data_uri(data)[1] == b"A,B\n1,4\n2,5\n3,6\n"++[email protected](not HAS_DEPS, reason="optional dependencies not installed")+ ("df_input", "initial_spec_kwargs", "expected_value"),+ [+ (+ pd.DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]}),+ {"x": "A", "y": "B", "color": "C"},+ {"x": "A", "y": "B", "color": "C"},+ ),+ (+ pd.DataFrame({"X": [10, 20], "Y": [30, 40]}),+ {"x": "X", "size": "Y"},+ {"x": "X", "size": "Y"},+ ),+ (+ pd.DataFrame(+ {"C1": [100, 200], "C2": [300, 400], "C3": [500, 600]}+ ),+ {"row": "C1", "column": "C2", "shape": "C3"},+ {"row": "C1", "column": "C2", "shape": "C3"},+ ),+ (pd.DataFrame({"E": [1, 2], "F": [3, 4]}), {}, {}),+ ],+)+def test_data_explorer_initial_spec(+ df_input: Any,+ initial_spec_kwargs: dict[str, str],+ expected_value: dict[str, str],+) -> None:+ """Test data_explorer with various initial spec keyword arguments."""+ valid_keys = ("x", "y", "row", "column", "color", "size", "shape")+ expected_value = {**dict.fromkeys(valid_keys, None), **expected_value}+ explorer = data_explorer.data_explorer(df_input, **initial_spec_kwargs)+ assert explorer.value == expected_value