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.

feat: add pan/zoom to mo.ui.altair_chart (#1855)

Myles Scolnick7d10fc1ab212
diff --git a/frontend/src/plugins/impl/vega/VegaPlugin.tsx b/frontend/src/plugins/impl/vega/VegaPlugin.tsx
index 745152ccc1..a03f2e61a3 100644
--- a/frontend/src/plugins/impl/vega/VegaPlugin.tsx
+++ b/frontend/src/plugins/impl/vega/VegaPlugin.tsx
@@ -8,6 +8,7 @@ import type { VegaComponentState, Data } from "./vega-component";
import "./vega.css";
import React from "react";
+import { TooltipProvider } from "@/components/ui/tooltip";
const LazyVegaComponent = React.lazy(() => import("./vega-component"));
@@ -27,11 +28,13 @@ export class VegaPlugin implements IPlugin<VegaComponentState, Data> {
render(props: IPluginProps<VegaComponentState, Data>): JSX.Element {
return (
- <LazyVegaComponent
- value={props.value}
- setValue={props.setValue}
- {...props.data}
- />
+ <TooltipProvider>
+ <LazyVegaComponent
+ value={props.value}
+ setValue={props.setValue}
+ {...props.data}
+ />
+ </TooltipProvider>
);
}
}
diff --git a/frontend/src/plugins/impl/vega/__tests__/__snapshots__/make-selectable.test.ts.snap b/frontend/src/plugins/impl/vega/__tests__/__snapshots__/make-selectable.test.ts.snap
index 0b2be85dfa..31e386095f 100644
--- a/frontend/src/plugins/impl/vega/__tests__/__snapshots__/make-selectable.test.ts.snap
+++ b/frontend/src/plugins/impl/vega/__tests__/__snapshots__/make-selectable.test.ts.snap
@@ -87,9 +87,20 @@ exports[`makeSelectable > should return correctly if existing legend selection 1
"encodings": [
"color",
],
+ "on": "click[!event.metaKey]",
"type": "point",
},
},
+ {
+ "bind": "scales",
+ "name": "pan_zoom",
+ "select": {
+ "on": "[mousedown[event.metaKey], window:mouseup] > window:mousemove!",
+ "translate": "[mousedown[event.metaKey], window:mouseup] > window:mousemove!",
+ "type": "interval",
+ "zoom": "wheel![event.metaKey]",
+ },
+ },
],
}
`;
@@ -127,6 +138,7 @@ exports[`makeSelectable > should return correctly if mark is a string 1`] = `
"x",
"y",
],
+ "on": "click[!event.metaKey]",
"type": "point",
},
},
@@ -143,9 +155,21 @@ exports[`makeSelectable > should return correctly if mark is a string 1`] = `
"stroke": "#669EFF",
"strokeOpacity": 0.4,
},
+ "on": "[mousedown[!event.metaKey], mouseup] > mousemove[!event.metaKey]",
+ "translate": "[mousedown[!event.metaKey], mouseup] > mousemove[!event.metaKey]",
"type": "interval",
},
},
+ {
+ "bind": "scales",
+ "name": "pan_zoom",
+ "select": {
+ "on": "[mousedown[event.metaKey], window:mouseup] > window:mousemove!",
+ "translate": "[mousedown[event.metaKey], window:mouseup] > window:mousemove!",
+ "type": "interval",
+ "zoom": "wheel![event.metaKey]",
+ },
+ },
],
}
`;
@@ -183,6 +207,7 @@ exports[`makeSelectable > should return correctly if mark is not string 1`] = `
"x",
"y",
],
+ "on": "click[!event.metaKey]",
"type": "point",
},
},
@@ -199,9 +224,21 @@ exports[`makeSelectable > should return correctly if mark is not string 1`] = `
"stroke": "#669EFF",
"strokeOpacity": 0.4,
},
+ "on": "[mousedown[!event.metaKey], mouseup] > mousemove[!event.metaKey]",
+ "translate": "[mousedown[!event.metaKey], mouseup] > mousemove[!event.metaKey]",
"type": "interval",
},
},
+ {
+ "bind": "scales",
+ "name": "pan_zoom",
+ "select": {
+ "on": "[mousedown[event.metaKey], window:mouseup] > window:mousemove!",
+ "translate": "[mousedown[event.metaKey], window:mouseup] > window:mousemove!",
+ "type": "interval",
+ "zoom": "wheel![event.metaKey]",
+ },
+ },
],
}
`;
@@ -272,6 +309,7 @@ exports[`makeSelectable > should return correctly if overlapping encodings 1`] =
"x",
"y",
],
+ "on": "click[!event.metaKey]",
"type": "point",
},
},
@@ -288,7 +326,19 @@ exports[`makeSelectable > should return correctly if overlapping encodings 1`] =
"stroke": "#669EFF",
"strokeOpacity": 0.4,
},
+ "on": "[mousedown[!event.metaKey], mouseup] > mousemove[!event.metaKey]",
+ "translate": "[mousedown[!event.metaKey], mouseup] > mousemove[!event.metaKey]",
+ "type": "interval",
+ },
+ },
+ {
+ "bind": "scales",
+ "name": "pan_zoom",
+ "select": {
+ "on": "[mousedown[event.metaKey], window:mouseup] > window:mousemove!",
+ "translate": "[mousedown[event.metaKey], window:mouseup] > window:mousemove!",
"type": "interval",
+ "zoom": "wheel![event.metaKey]",
},
},
],
@@ -362,6 +412,7 @@ exports[`makeSelectable > should return correctly with multiple encodings 1`] =
"x",
"y",
],
+ "on": "click[!event.metaKey]",
"type": "point",
},
},
@@ -378,7 +429,19 @@ exports[`makeSelectable > should return correctly with multiple encodings 1`] =
"stroke": "#669EFF",
"strokeOpacity": 0.4,
},
+ "on": "[mousedown[!event.metaKey], mouseup] > mousemove[!event.metaKey]",
+ "translate": "[mousedown[!event.metaKey], mouseup] > mousemove[!event.metaKey]",
+ "type": "interval",
+ },
+ },
+ {
+ "bind": "scales",
+ "name": "pan_zoom",
+ "select": {
+ "on": "[mousedown[event.metaKey], window:mouseup] > window:mousemove!",
+ "translate": "[mousedown[event.metaKey], window:mouseup] > window:mousemove!",
"type": "interval",
+ "zoom": "wheel![event.metaKey]",
},
},
],
@@ -438,6 +501,7 @@ exports[`makeSelectable > should skip field selection if empty or false 1`] = `
"x",
"y",
],
+ "on": "click[!event.metaKey]",
"type": "point",
},
},
@@ -454,9 +518,21 @@ exports[`makeSelectable > should skip field selection if empty or false 1`] = `
"stroke": "#669EFF",
"strokeOpacity": 0.4,
},
+ "on": "[mousedown[!event.metaKey], mouseup] > mousemove[!event.metaKey]",
+ "translate": "[mousedown[!event.metaKey], mouseup] > mousemove[!event.metaKey]",
"type": "interval",
},
},
+ {
+ "bind": "scales",
+ "name": "pan_zoom",
+ "select": {
+ "on": "[mousedown[event.metaKey], window:mouseup] > window:mousemove!",
+ "translate": "[mousedown[event.metaKey], window:mouseup] > window:mousemove!",
+ "type": "interval",
+ "zoom": "wheel![event.metaKey]",
+ },
+ },
],
}
`;
@@ -509,6 +585,18 @@ exports[`makeSelectable > should work for multi-layered charts 1`] = `
"ticks": true,
"type": "errorbar",
},
+ "params": [
+ {
+ "bind": "scales",
+ "name": "pan_zoom",
+ "select": {
+ "on": "[mousedown[event.metaKey], window:mouseup] > window:mousemove!",
+ "translate": "[mousedown[event.metaKey], window:mouseup] > window:mousemove!",
+ "type": "interval",
+ "zoom": "wheel![event.metaKey]",
+ },
+ },
+ ],
},
{
"encoding": {
@@ -548,6 +636,7 @@ exports[`makeSelectable > should work for multi-layered charts 1`] = `
"x",
"y",
],
+ "on": "click[!event.metaKey]",
"type": "point",
},
},
@@ -564,6 +653,8 @@ exports[`makeSelectable > should work for multi-layered charts 1`] = `
"stroke": "#669EFF",
"strokeOpacity": 0.4,
},
+ "on": "[mousedown[!event.metaKey], mouseup] > mousemove[!event.metaKey]",
+ "translate": "[mousedown[!event.metaKey], mouseup] > mousemove[!event.metaKey]",
"type": "interval",
},
},
@@ -632,6 +723,7 @@ exports[`makeSelectable > should work for multi-layered charts with different se
"encodings": [
"y",
],
+ "on": "click[!event.metaKey]",
"type": "point",
},
},
@@ -647,7 +739,19 @@ exports[`makeSelectable > should work for multi-layered charts with different se
"stroke": "#669EFF",
"strokeOpacity": 0.4,
},
+ "on": "[mousedown[!event.metaKey], mouseup] > mousemove[!event.metaKey]",
+ "translate": "[mousedown[!event.metaKey], mouseup] > mousemove[!event.metaKey]",
+ "type": "interval",
+ },
+ },
+ {
+ "bind": "scales",
+ "name": "pan_zoom",
+ "select": {
+ "on": "[mousedown[event.metaKey], window:mouseup] > window:mousemove!",
+ "translate": "[mousedown[event.metaKey], window:mouseup] > window:mousemove!",
"type": "interval",
+ "zoom": "wheel![event.metaKey]",
},
},
],
diff --git a/frontend/src/plugins/impl/vega/__tests__/make-selectable.test.ts b/frontend/src/plugins/impl/vega/__tests__/make-selectable.test.ts
index 229540f852..4092a928a6 100644
--- a/frontend/src/plugins/impl/vega/__tests__/make-selectable.test.ts
+++ b/frontend/src/plugins/impl/vega/__tests__/make-selectable.test.ts
@@ -92,6 +92,7 @@ describe("makeSelectable", () => {
"legend_selection_Origin",
"select_point",
"select_interval",
+ "pan_zoom",
]);
});
@@ -130,6 +131,7 @@ describe("makeSelectable", () => {
expect(getSelectionParamNames(newSpec)).toEqual([
"select_point",
"select_interval",
+ "pan_zoom",
]);
// These are the same
@@ -162,6 +164,7 @@ describe("makeSelectable", () => {
"legend_selection_sizeField",
"select_point",
"select_interval",
+ "pan_zoom",
]);
});
@@ -214,6 +217,7 @@ describe("makeSelectable", () => {
"param_1",
"legend_selection_series",
"select_point",
+ "pan_zoom",
]);
});
@@ -287,6 +291,7 @@ describe("makeSelectable", () => {
expect(newSpec).toMatchSnapshot();
expect(getSelectionParamNames(newSpec)).toEqual([
+ "pan_zoom",
"select_point_1",
"select_interval_1",
]);
@@ -349,6 +354,7 @@ describe("makeSelectable", () => {
expect(getSelectionParamNames(newSpec)).toEqual([
"select_point_0",
"select_interval_0",
+ "pan_zoom",
]);
});
});
diff --git a/frontend/src/plugins/impl/vega/__tests__/vega.test.ts b/frontend/src/plugins/impl/vega/__tests__/vega.test.ts
index f2158c987e..6c2904ef81 100644
--- a/frontend/src/plugins/impl/vega/__tests__/vega.test.ts
+++ b/frontend/src/plugins/impl/vega/__tests__/vega.test.ts
@@ -126,6 +126,31 @@ yield_error,yield_center
]
`);
});
+
+ it("should handle when there is no format given", async () => {
+ const csvData = `id\n912312851340981241284`;
+ vi.spyOn(vegaLoader, "load").mockReturnValue(Promise.resolve(csvData));
+ const format = undefined;
+ const data = await vegaLoadData(csvData, format, { handleBigInt: true });
+ expect(data).toMatchInlineSnapshot(`
+ [
+ {
+ "id": 912312851340981241284n,
+ },
+ ]
+ `);
+
+ const jsonData = `[{"id": "912312851340981241284"}]`;
+ vi.spyOn(vegaLoader, "load").mockReturnValue(Promise.resolve(jsonData));
+ const data2 = await vegaLoadData(jsonData, format);
+ expect(data2).toMatchInlineSnapshot(`
+ [
+ {
+ "id": "912312851340981241284",
+ },
+ ]
+ `);
+ });
});
describe("uniquifyColumnNames", () => {
diff --git a/frontend/src/plugins/impl/vega/loader.ts b/frontend/src/plugins/impl/vega/loader.ts
index 352a0234d8..8780267f2f 100644
--- a/frontend/src/plugins/impl/vega/loader.ts
+++ b/frontend/src/plugins/impl/vega/loader.ts
@@ -96,9 +96,23 @@ export function vegaLoadData<T = object>(
): Promise<T[]> {
const { handleBigInt = false, replacePeriod = false } = opts;
- const isCsv = format?.type === "csv";
-
return vegaLoader.load(url).then((csvOrJsonData) => {
+ if (!format) {
+ // Infer by trying to parse
+ if (typeof csvOrJsonData === "string") {
+ try {
+ JSON.parse(csvOrJsonData);
+ format = { type: "json" };
+ } catch {
+ format = { type: "csv", parse: "auto" };
+ }
+ }
+ if (typeof csvOrJsonData === "object") {
+ format = { type: "json" };
+ }
+ }
+
+ const isCsv = format?.type === "csv";
// CSV data comes columnar and may have duplicate column names.
// We need to uniquify the column names before parsing since vega-loader
// returns an array of objects which drops duplicate keys.
@@ -126,7 +140,7 @@ export function vegaLoadData<T = object>(
? // csv -> json
read(csvOrJsonData, {
...format,
- parse: (format.parse as FieldTypes) || "auto",
+ parse: (format?.parse as FieldTypes) || "auto",
})
: read(csvOrJsonData, format);
diff --git a/frontend/src/plugins/impl/vega/make-selectable.ts b/frontend/src/plugins/impl/vega/make-selectable.ts
index f1418e3a93..4e39498f82 100644
--- a/frontend/src/plugins/impl/vega/make-selectable.ts
+++ b/frontend/src/plugins/impl/vega/make-selectable.ts
@@ -29,6 +29,7 @@ export function makeSelectable<T extends VegaLiteSpec>(
const subSpecs = spec.vconcat.map((subSpec) =>
"mark" in subSpec ? makeChartInteractive(subSpec) : subSpec,
);
+ // No pan/zoom for vconcat
return { ...spec, vconcat: subSpecs };
}
@@ -36,6 +37,7 @@ export function makeSelectable<T extends VegaLiteSpec>(
const subSpecs = spec.hconcat.map((subSpec) =>
"mark" in subSpec ? makeChartInteractive(subSpec) : subSpec,
);
+ // No pan/zoom for hconcat
return { ...spec, hconcat: subSpecs };
}
@@ -47,6 +49,9 @@ export function makeSelectable<T extends VegaLiteSpec>(
let resolvedSpec = subSpec as VegaLiteUnitSpec;
resolvedSpec = makeChartSelectable(resolvedSpec, chartSelection, idx);
resolvedSpec = makeChartInteractive(resolvedSpec);
+ if (idx === 0) {
+ resolvedSpec = makeChartPanZoom(resolvedSpec);
+ }
return resolvedSpec;
});
return { ...spec, layer: subSpecs };
@@ -60,6 +65,7 @@ export function makeSelectable<T extends VegaLiteSpec>(
resolvedSpec = makeLegendSelectable(resolvedSpec, fieldSelection);
resolvedSpec = makeChartSelectable(resolvedSpec, chartSelection, undefined);
resolvedSpec = makeChartInteractive(resolvedSpec);
+ resolvedSpec = makeChartPanZoom(resolvedSpec);
return resolvedSpec as T;
}
@@ -143,6 +149,20 @@ function makeChartSelectable(
} as VegaLiteUnitSpec;
}
+function makeChartPanZoom(spec: VegaLiteUnitSpec): VegaLiteUnitSpec {
+ const params = spec.params || [];
+
+ const alreadyHasScalesParam = params.some((param) => param.bind === "scales");
+ if (alreadyHasScalesParam) {
+ return spec;
+ }
+
+ return {
+ ...spec,
+ params: [...params, Params.panZoom()],
+ };
+}
+
/**
* Makes a chart clickable and adds an opacity encoding to the chart.
*/
diff --git a/frontend/src/plugins/impl/vega/params.ts b/frontend/src/plugins/impl/vega/params.ts
index 8d6ccb754a..f46f337047 100644
--- a/frontend/src/plugins/impl/vega/params.ts
+++ b/frontend/src/plugins/impl/vega/params.ts
@@ -10,7 +10,7 @@ import {
} from "./types";
import { LayerSpec, UnitSpec } from "vega-lite/build/src/spec";
-const ParamNames = {
+export const ParamNames = {
point(layerNum: number | undefined) {
return layerNum == null ? "select_point" : `select_point_${layerNum}`;
},
@@ -21,6 +21,19 @@ const ParamNames = {
return `legend_selection_${field}`;
},
HIGHLIGHT: "highlight",
+ PAN_ZOOM: "pan_zoom",
+ hasPoint(names: string[]) {
+ return names.some((name) => name.startsWith("select_point"));
+ },
+ hasInterval(names: string[]) {
+ return names.some((name) => name.startsWith("select_interval"));
+ },
+ hasLegend(names: string[]) {
+ return names.some((name) => name.startsWith("legend_selection"));
+ },
+ hasPanZoom(names: string[]) {
+ return names.some((name) => name.startsWith("pan_zoom"));
+ },
};
export const Params = {
@@ -45,6 +58,10 @@ export const Params = {
stroke: "#669EFF",
strokeOpacity: 0.4,
},
+ // So this does not conflict with pan/zoom via metaKey
+ on: "[mousedown[!event.metaKey], mouseup] > mousemove[!event.metaKey]",
+ translate:
+ "[mousedown[!event.metaKey], mouseup] > mousemove[!event.metaKey]",
},
};
},
@@ -57,6 +74,7 @@ export const Params = {
select: {
type: "point",
encodings: getEncodingAxisForMark(spec),
+ on: "click[!event.metaKey]",
},
};
},
@@ -70,6 +88,19 @@ export const Params = {
bind: "legend",
};
},
+ panZoom(): SelectionParameter<"interval"> {
+ return {
+ name: ParamNames.PAN_ZOOM,
+ bind: "scales",
+ select: {
+ type: "interval",
+ on: "[mousedown[event.metaKey], window:mouseup] > window:mousemove!",
+ translate:
+ "[mousedown[event.metaKey], window:mouseup] > window:mousemove!",
+ zoom: "wheel![event.metaKey]",
+ },
+ };
+ },
};
export function getEncodingAxisForMark(
diff --git a/frontend/src/plugins/impl/vega/vega-component.tsx b/frontend/src/plugins/impl/vega/vega-component.tsx
index 1243127420..4bdab62dc2 100644
--- a/frontend/src/plugins/impl/vega/vega-component.tsx
+++ b/frontend/src/plugins/impl/vega/vega-component.tsx
@@ -2,7 +2,7 @@
import { VegaLite, type SignalListeners, type View } from "react-vega";
import { makeSelectable } from "./make-selectable";
import { useMemo, useRef, useState } from "react";
-import { getSelectionParamNames } from "./params";
+import { getSelectionParamNames, ParamNames } from "./params";
import type { VegaLiteSpec } from "./types";
import { Alert, AlertTitle } from "@/components/ui/alert";
import { useDeepCompareMemoize } from "@/hooks/useDeepCompareMemoize";
@@ -17,6 +17,8 @@ import { Objects } from "@/utils/objects";
import { resolveVegaSpecData } from "./resolve-data";
import { Events } from "@/utils/events";
import { ErrorBanner } from "../common/error-banner";
+import { Tooltip } from "@/components/ui/tooltip";
+import { HelpCircleIcon } from "lucide-react";
export interface Data {
spec: VegaLiteSpec;
@@ -120,6 +122,11 @@ const LoadedVegaComponent = ({
const signalListeners = useMemo(
() =>
names.reduce<SignalListeners>((acc, name) => {
+ // pan/zoom does not count towards selection
+ if (ParamNames.PAN_ZOOM === name) {
+ return acc;
+ }
+
// Debounce each signal listener, otherwise we may create expensive requests
acc[name] = debounce((signalName, signalValue) => {
Logger.debug("[Vega signal]", signalName, signalValue);
@@ -149,6 +156,64 @@ const LoadedVegaComponent = ({
setError(undefined);
});
+ const renderHelpContent = () => {
+ const hints: Array<[string, string]> = [];
+ if (ParamNames.hasPoint(names)) {
+ hints.push([
+ "Point selection",
+ "click to select a point; hold shift for multi-select",
+ ]);
+ }
+
+ if (ParamNames.hasInterval(names)) {
+ hints.push([
+ "Interval selection",
+ "click and drag to select an interval",
+ ]);
+ }
+
+ if (ParamNames.hasLegend(names)) {
+ hints.push([
+ "Legend selection",
+ "click to select a legend item; hold shift for multi-select",
+ ]);
+ }
+
+ if (ParamNames.hasPanZoom(names)) {
+ hints.push(
+ ["Pan", "hold the meta key and drag"],
+ ["Zoom", "hold the meta key and scroll"],
+ );
+ }
+
+ if (hints.length === 0) {
+ return null;
+ }
+
+ return (
+ <Tooltip
+ delayDuration={300}
+ side="left"
+ content={
+ <div className="text-xs flex flex-col">
+ {hints.map((hint, i) => (
+ <div key={i}>
+ <span className="font-bold tracking-wide">{hint[0]}:</span>{" "}
+ {hint[1]}
+ </div>
+ ))}
+ </div>
+ }
+ >
+ <HelpCircleIcon
+ className={
+ "absolute bottom-1 right-0 m-2 h-4 w-4 cursor-help text-muted-foreground hover:text-foreground"
+ }
+ />
+ </Tooltip>
+ );
+ };
+
return (
<>
{error && (
@@ -158,7 +223,7 @@ const LoadedVegaComponent = ({
</Alert>
)}
<div
- className="contents"
+ className="relative"
// Capture the pointer down event to prevent the parent from handling it
onPointerDown={Events.stopPropagation()}
>
@@ -170,6 +235,7 @@ const LoadedVegaComponent = ({
onError={handleError}
onNewView={handleNewView}
/>
+ {renderHelpContent()}
</div>
</>
);
diff --git a/frontend/src/plugins/impl/vega/vega-loader.ts b/frontend/src/plugins/impl/vega/vega-loader.ts
index 984a4c0234..0954ac1419 100644
--- a/frontend/src/plugins/impl/vega/vega-loader.ts
+++ b/frontend/src/plugins/impl/vega/vega-loader.ts
@@ -6,7 +6,7 @@ import type { DataType } from "@/core/kernel/messages";
// Re-export the vega-loader functions to add TypeScript types
-export function read(
+export function read<T = object>(
data: string | Record<string, unknown> | Array<Record<string, unknown>>,
format:
| DataFormat
@@ -19,7 +19,7 @@ export function read(
parse: FieldTypes;
}
| undefined,
-): object[] {
+): T[] {
return vl.read(data, format);
}
diff --git a/marimo/_plugins/ui/_impl/altair_chart.py b/marimo/_plugins/ui/_impl/altair_chart.py
index 2e42e85a02..74265c6b0b 100644
--- a/marimo/_plugins/ui/_impl/altair_chart.py
+++ b/marimo/_plugins/ui/_impl/altair_chart.py
@@ -54,7 +54,10 @@ def _filter_dataframe(
) -> pd.DataFrame:
import numpy as np
- for _channel, fields in selection.items():
+ for channel, fields in selection.items():
+ # Don't filter on pan_zoom
+ if channel.startswith("pan_zoom"):
+ continue
# This is a case when altair does not pass back the fields to filter on
# and instead passes an individual selected point.
if len(fields) == 2 and "vlPoint" in fields and "_vgsid_" in fields:
@@ -111,6 +114,9 @@ def _coerce_value(dtype: Any, value: Any) -> Any:
return pd.to_datetime(value, unit="ms")
+ if dtype == "object":
+ return str(value)
+
return value
@@ -254,7 +260,7 @@ class altair_chart(UIElement[ChartSelection, "pd.DataFrame"]):
chart_selection = False
legend_selection = False
- self.dataframe: alt.UndefinedType | pd.DataFrame = chart.data
+ self.dataframe = self._get_dataframe_from_chart(chart)
self._spec = vega_spec
@@ -274,6 +280,19 @@ class altair_chart(UIElement[ChartSelection, "pd.DataFrame"]):
def selections(self) -> ChartSelection:
return self._chart_selection
+ @staticmethod
+ def _get_dataframe_from_chart(
+ chart: altair.Chart,
+ ) -> Union[pd.DataFrame, altair.UndefinedType]:
+ import pandas as pd
+
+ if isinstance(chart.data, str) and chart.data.endswith(".csv"):
+ return pd.read_csv(chart.data)
+ if isinstance(chart.data, str) and chart.data.endswith(".json"):
+ return pd.read_json(chart.data)
+
+ return chart.data
+
def _convert_value(self, value: ChartSelection) -> Any:
from altair import UndefinedType
diff --git a/marimo/_smoke_tests/altair/altair_charts.py b/marimo/_smoke_tests/altair/altair_charts.py
index a5e98d7510..36634606b2 100644
--- a/marimo/_smoke_tests/altair/altair_charts.py
+++ b/marimo/_smoke_tests/altair/altair_charts.py
@@ -2,7 +2,7 @@
import marimo
-__generated_with = "0.2.2"
+__generated_with = "0.7.9"
app = marimo.App(width="full")
@@ -515,9 +515,9 @@ def __(facet_chart, mo):
def __(mo):
mo.md(
"""
- # With `transform_filter`
- > Bug https://github.com/marimo-team/marimo/issues/727
- """
+ # With `transform_filter`
+ > Bug https://github.com/marimo-team/marimo/issues/727
+ """
)
return
@@ -596,5 +596,52 @@ def __(layered_chart, mo):
return
+def __(mo):
+ mo.md(r"# layered")
+ return
+
+
+def __(alt, data, datum, mo):
+ stocks = data.stocks.url
+
+ base = alt.Chart(stocks).encode(
+ x='date:T',
+ y='price:Q',
+ color='symbol:N'
+ ).transform_filter(
+ datum.symbol == 'GOOG'
+ )
+
+ t = mo.ui.altair_chart(base.mark_line() + base.mark_point())
+ t
+ return base, stocks, t
+
+
+def __(mo):
+ mo.md(r"# hconcat")
+ return
+
+
+def __(base, mo):
+ mo.ui.altair_chart(base.mark_line() | base.mark_point())
+ return
+
+
+def __(mo):
+ mo.md("# vconcat")
+ return
+
+
+def __(base, mo):
+ mo.ui.altair_chart(base.mark_line() & base.mark_point())
+ 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 577dbe6acb..5c2bc07c32 100644
--- a/tests/_plugins/ui/_impl/test_altair_chart.py
+++ b/tests/_plugins/ui/_impl/test_altair_chart.py
@@ -215,3 +215,40 @@ def test_does_not_modify_original() -> None:
)
assert combined1 == combined2._chart
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_get_dataframe() -> None:
+ import altair as alt
+
+ data = {"values": [1, 2, 3]}
+ chart = altair_chart.altair_chart(
+ alt.Chart(data).mark_point().encode(x="values:Q")
+ )
+ assert chart.dataframe == data
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_get_dataframe_csv() -> None:
+ import altair as alt
+ import pandas as pd
+
+ data = "https://cdn.jsdelivr.net/npm/[email protected]/data/stocks.csv"
+ chart = altair_chart.altair_chart(
+ alt.Chart(data).mark_point().encode(x="values:Q")
+ )
+ assert isinstance(chart.dataframe, pd.DataFrame)
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_get_dataframe_json() -> None:
+ import altair as alt
+ import pandas as pd
+
+ data = (
+ "https://cdn.jsdelivr.net/npm/[email protected]/data/barley.json"
+ )
+ chart = altair_chart.altair_chart(
+ alt.Chart(data).mark_point().encode(x="values:Q")
+ )
+ assert isinstance(chart.dataframe, pd.DataFrame)