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.

improvement: generate altair code from chart spec (#4888)

Myles Scolnickfc7650a2c619
diff --git a/frontend/src/components/data-table/charts/__tests__/__snapshots__/spec-snapshot.test.ts.snap b/frontend/src/components/data-table/charts/__tests__/__snapshots__/spec-snapshot.test.ts.snap
index 11c358b43d..758ef512b0 100644
--- a/frontend/src/components/data-table/charts/__tests__/__snapshots__/spec-snapshot.test.ts.snap
+++ b/frontend/src/components/data-table/charts/__tests__/__snapshots__/spec-snapshot.test.ts.snap
@@ -1,382 +1,34 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
-exports[`createVegaSpec > Bar Chart > should create a horizontal bar chart 1`] = `
+exports[`create vega spec > should create and augment a spec 1`] = `
{
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
"background": "white",
"data": {
- "values": [
- {
- "category": "A",
- "group": "Group 1",
- "value": 10,
- },
- {
- "category": "B",
- "group": "Group 1",
- "value": 20,
- },
- {
- "category": "C",
- "group": "Group 1",
- "value": 15,
- },
- {
- "category": "A",
- "group": "Group 2",
- "value": 5,
- },
- {
- "category": "B",
- "group": "Group 2",
- "value": 10,
- },
- {
- "category": "C",
- "group": "Group 2",
- "value": 25,
- },
- ],
- },
- "encoding": {
- "x": {
- "field": "value",
- "type": "nominal",
- },
- "y": {
- "field": "category",
- "type": "nominal",
- },
- },
- "height": 300,
- "mark": {
- "type": "bar",
- },
- "resolve": {
- "axis": {
- "x": "independent",
- "y": "independent",
- },
- },
- "title": "Test Chart",
- "width": 400,
-}
-`;
-
-exports[`createVegaSpec > Bar Chart > should create a stacked bar chart with grouping 1`] = `
-{
- "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
- "background": "white",
- "data": {
- "values": [
- {
- "category": "A",
- "group": "Group 1",
- "value": 10,
- },
- {
- "category": "B",
- "group": "Group 1",
- "value": 20,
- },
- {
- "category": "C",
- "group": "Group 1",
- "value": 15,
- },
- {
- "category": "A",
- "group": "Group 2",
- "value": 5,
- },
- {
- "category": "B",
- "group": "Group 2",
- "value": 10,
- },
- {
- "category": "C",
- "group": "Group 2",
- "value": 25,
- },
- ],
- },
- "encoding": {
- "color": {
- "field": "group",
- "scale": {},
- "type": "nominal",
- },
- "x": {
- "field": "category",
- "type": "nominal",
- },
- "y": {
- "field": "value",
- "stack": true,
- "type": "nominal",
- },
- },
- "height": 300,
- "mark": {
- "type": "bar",
- },
- "resolve": {
- "axis": {
- "x": "independent",
- "y": "independent",
- },
- },
- "title": "Test Chart",
- "width": 400,
-}
-`;
-
-exports[`createVegaSpec > Edge cases > should handle missing xColumn field 1`] = `"X-axis column is required"`;
-
-exports[`createVegaSpec > Edge cases > should handle missing yColumn field 1`] = `"Y-axis column is required"`;
-
-exports[`createVegaSpec > Line Chart > should create a basic line chart spec 1`] = `
-{
- "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
- "background": "white",
- "data": {
- "values": [
- {
- "category": "A",
- "group": "Group 1",
- "value": 10,
- },
- {
- "category": "B",
- "group": "Group 1",
- "value": 20,
- },
- {
- "category": "C",
- "group": "Group 1",
- "value": 15,
- },
- {
- "category": "A",
- "group": "Group 2",
- "value": 5,
- },
- {
- "category": "B",
- "group": "Group 2",
- "value": 10,
- },
- {
- "category": "C",
- "group": "Group 2",
- "value": 25,
- },
- ],
- },
- "encoding": {
- "x": {
- "field": "category",
- "type": "nominal",
- },
- "y": {
- "field": "value",
- "type": "nominal",
- },
- },
- "height": 300,
- "mark": {
- "type": "line",
- },
- "resolve": {
- "axis": {
- "x": "independent",
- "y": "independent",
- },
- },
- "title": "Test Chart",
- "width": 400,
-}
-`;
-
-exports[`createVegaSpec > Pie Chart > should create a pie chart with tooltips 1`] = `"Color by column is required"`;
-
-exports[`createVegaSpec > Scatter Chart > should create a scatter chart with grouping 1`] = `
-{
- "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
- "background": "white",
- "data": {
- "values": [
- {
- "category": "A",
- "group": "Group 1",
- "value": 10,
- },
- {
- "category": "B",
- "group": "Group 1",
- "value": 20,
- },
- {
- "category": "C",
- "group": "Group 1",
- "value": 15,
- },
- {
- "category": "A",
- "group": "Group 2",
- "value": 5,
- },
- {
- "category": "B",
- "group": "Group 2",
- "value": 10,
- },
- {
- "category": "C",
- "group": "Group 2",
- "value": 25,
- },
- ],
- },
- "encoding": {
- "color": {
- "field": "group",
- "scale": {},
- "type": "nominal",
- },
- "x": {
- "field": "category",
- "type": "nominal",
- },
- "y": {
- "field": "value",
- "type": "nominal",
- },
- },
- "height": 300,
- "mark": {
- "type": "point",
- },
- "resolve": {
- "axis": {
- "x": "independent",
- "y": "independent",
- },
- },
- "title": "Test Chart",
- "width": 400,
-}
-`;
-
-exports[`createVegaSpec > Theme variations > should create a chart with dark theme 1`] = `
-{
- "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
- "background": "dark",
- "data": {
- "values": [
- {
- "category": "A",
- "group": "Group 1",
- "value": 10,
- },
- {
- "category": "B",
- "group": "Group 1",
- "value": 20,
- },
- {
- "category": "C",
- "group": "Group 1",
- "value": 15,
- },
- {
- "category": "A",
- "group": "Group 2",
- "value": 5,
- },
- {
- "category": "B",
- "group": "Group 2",
- "value": 10,
- },
- {
- "category": "C",
- "group": "Group 2",
- "value": 25,
- },
- ],
- },
- "encoding": {
- "x": {
- "field": "category",
- "type": "nominal",
- },
- "y": {
- "field": "value",
- "type": "nominal",
- },
- },
- "height": 300,
- "mark": {
- "type": "bar",
- },
- "resolve": {
- "axis": {
- "x": "independent",
- "y": "independent",
- },
- },
- "title": "Test Chart",
- "width": 400,
-}
-`;
-
-exports[`createVegaSpec > should create a bar chart with binning 1`] = `
-{
- "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
- "background": "white",
- "data": {
- "values": [
- {
- "category": "A",
- "group": "Group 1",
- "value": 10,
- },
- {
- "category": "B",
- "group": "Group 1",
- "value": 20,
- },
- {
- "category": "C",
- "group": "Group 1",
- "value": 15,
- },
- {
- "category": "A",
- "group": "Group 2",
- "value": 5,
- },
- {
- "category": "B",
- "group": "Group 2",
- "value": 10,
- },
- {
- "category": "C",
- "group": "Group 2",
- "value": 25,
- },
- ],
+ "values": [],
},
"encoding": {
+ "color": undefined,
+ "column": undefined,
+ "row": undefined,
+ "tooltip": undefined,
"x": {
+ "aggregate": undefined,
+ "bin": undefined,
"field": "category",
+ "stack": undefined,
+ "timeUnit": undefined,
+ "title": undefined,
"type": "nominal",
},
+ "xOffset": undefined,
"y": {
+ "aggregate": undefined,
+ "bin": undefined,
"field": "value",
+ "stack": undefined,
+ "timeUnit": undefined,
+ "title": undefined,
"type": "nominal",
},
},
@@ -384,12 +36,6 @@ exports[`createVegaSpec > should create a bar chart with binning 1`] = `
"mark": {
"type": "bar",
},
- "resolve": {
- "axis": {
- "x": "independent",
- "y": "independent",
- },
- },
"title": "Test Chart",
"width": 400,
}
diff --git a/frontend/src/components/data-table/charts/__tests__/altair-generator.test.ts b/frontend/src/components/data-table/charts/__tests__/altair-generator.test.ts
new file mode 100644
index 0000000000..e967f5d1c9
--- /dev/null
+++ b/frontend/src/components/data-table/charts/__tests__/altair-generator.test.ts
@@ -0,0 +1,424 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, expect, it } from "vitest";
+import {
+ generateAltairChart,
+ generateAltairChartSnippet,
+} from "../chart-spec/altair-generator";
+import type { VegaLiteSpec } from "@/plugins/impl/vega/types";
+
+function createSpec(spec: {
+ mark: string | Record<string, unknown>;
+ encoding: Record<
+ string,
+ | { field: string; type?: string }
+ | Array<{ field: string; tooltip?: Record<string, string> }>
+ >;
+ resolve?: Record<string, unknown>;
+ title?: string;
+ width?: number;
+ height?: number;
+}): VegaLiteSpec {
+ return {
+ ...spec,
+ data: { name: "_unused_" },
+ } as VegaLiteSpec;
+}
+
+const Mocks = {
+ // Simple
+ xAxis: {
+ field: "category",
+ },
+ yAxis: {
+ field: "value",
+ },
+
+ // Full
+ xAxisFull: {
+ field: "category",
+ axis: {
+ title: "X Axis",
+ },
+ },
+ yAxisFull: {
+ field: "value",
+ axis: {
+ title: "Y Axis",
+ },
+ },
+
+ // Color
+ colorAxis: {
+ field: "color",
+ },
+ thetaAxis: {
+ field: "theta",
+ axis: {
+ title: "Theta Axis",
+ },
+ },
+ rowAxis: {
+ field: "row",
+ axis: {
+ title: "Row Axis",
+ },
+ },
+ columnAxis: {
+ field: "column",
+ axis: {
+ title: "Column Axis",
+ },
+ },
+ tooltip: {
+ field: "tooltip",
+ tooltip: {
+ title: "Tooltip",
+ },
+ },
+ marks: {
+ bar: {
+ type: "bar",
+ opacity: 0.8,
+ color: "red",
+ },
+ arc: {
+ type: "arc",
+ innerRadius: 100,
+ },
+ },
+};
+
+describe("generateAltairChart", () => {
+ it("should remove undefined values", () => {
+ const spec = createSpec({
+ mark: "bar",
+ encoding: {
+ x: { ...Mocks.xAxis, type: undefined },
+ },
+ });
+
+ const result = generateAltairChart(spec, "df").toCode();
+
+ expect(result).toMatchInlineSnapshot(`
+ "alt.Chart(df)
+ .mark_bar()
+ .encode(x=alt.X(field='category'))"
+ `);
+ });
+
+ it("should generate a basic bar chart", () => {
+ const spec = createSpec({
+ mark: "bar",
+ encoding: {
+ x: Mocks.xAxis,
+ y: Mocks.yAxis,
+ },
+ });
+ const datasource = "df";
+
+ const result = generateAltairChart(spec, datasource).toCode();
+
+ expect(result).toMatchInlineSnapshot(`
+ "alt.Chart(df)
+ .mark_bar()
+ .encode(
+ x=alt.X(field='category'),
+ y=alt.Y(field='value')
+ )"
+ `);
+ });
+
+ it("should generate a donut chart", () => {
+ const spec = createSpec({
+ mark: Mocks.marks.arc,
+ encoding: {
+ theta: Mocks.thetaAxis,
+ },
+ });
+ const datasource = "df";
+
+ const result = generateAltairChart(spec, datasource).toCode();
+
+ expect(result).toMatchInlineSnapshot(`
+ "alt.Chart(df)
+ .mark_arc(innerRadius=100)
+ .encode(theta=alt.Theta(field='theta', axis={
+ 'title': 'Theta Axis'
+ }))"
+ `);
+ });
+
+ it("should use the provided datasource variable name", () => {
+ const spec = createSpec({
+ mark: "bar",
+ encoding: {
+ x: Mocks.xAxis,
+ y: Mocks.yAxis,
+ },
+ });
+ const datasource = "my_custom_dataframe";
+
+ const result = generateAltairChart(spec, datasource).toCode();
+
+ expect(result).toMatchInlineSnapshot(`
+ "alt.Chart(my_custom_dataframe)
+ .mark_bar()
+ .encode(
+ x=alt.X(field='category'),
+ y=alt.Y(field='value')
+ )"
+ `);
+ });
+
+ it("should generate a snippet", () => {
+ const spec = createSpec({
+ mark: "bar",
+ encoding: {
+ x: Mocks.xAxis,
+ y: Mocks.yAxis,
+ },
+ });
+ const datasource = "df";
+
+ const result = generateAltairChartSnippet(spec, datasource, "_chart");
+
+ expect(result).toMatchInlineSnapshot(`
+ "_chart = (
+ alt.Chart(df)
+ .mark_bar()
+ .encode(
+ x=alt.X(field='category'),
+ y=alt.Y(field='value')
+ )
+ )
+ _chart"
+ `);
+ });
+
+ it("should generate a chart with color encoding", () => {
+ const spec = createSpec({
+ mark: "bar",
+ encoding: {
+ x: Mocks.xAxis,
+ y: Mocks.yAxis,
+ color: Mocks.colorAxis,
+ },
+ });
+ const datasource = "df";
+
+ const result = generateAltairChart(spec, datasource).toCode();
+
+ expect(result).toMatchInlineSnapshot(`
+ "alt.Chart(df)
+ .mark_bar()
+ .encode(
+ x=alt.X(field='category'),
+ y=alt.Y(field='value'),
+ color=alt.Color(field='color')
+ )"
+ `);
+ });
+
+ it("should generate a chart with tooltip", () => {
+ const spec = createSpec({
+ mark: "bar",
+ encoding: {
+ x: Mocks.xAxis,
+ y: Mocks.yAxis,
+ tooltip: Mocks.tooltip,
+ },
+ });
+ const datasource = "df";
+
+ const result = generateAltairChart(spec, datasource).toCode();
+
+ expect(result).toMatchInlineSnapshot(`
+ "alt.Chart(df)
+ .mark_bar()
+ .encode(
+ x=alt.X(field='category'),
+ y=alt.Y(field='value'),
+ tooltip=alt.Tooltip(field='tooltip', tooltip={
+ 'title': 'Tooltip'
+ })
+ )"
+ `);
+ });
+
+ it("should handle array tooltips", () => {
+ const spec = createSpec({
+ mark: "bar",
+ encoding: {
+ x: Mocks.xAxis,
+ y: Mocks.yAxis,
+ tooltip: [Mocks.tooltip, Mocks.tooltip],
+ },
+ });
+ const datasource = "df";
+
+ const result = generateAltairChart(spec, datasource).toCode();
+
+ expect(result).toMatchInlineSnapshot(`
+ "alt.Chart(df)
+ .mark_bar()
+ .encode(
+ x=alt.X(field='category'),
+ y=alt.Y(field='value'),
+ tooltip=[
+ alt.Tooltip(field='tooltip', tooltip={
+ 'title': 'Tooltip'
+ }),
+ alt.Tooltip(field='tooltip', tooltip={
+ 'title': 'Tooltip'
+ })
+ ]
+ )"
+ `);
+ });
+
+ it("should generate a chart with row and column facets", () => {
+ const spec = createSpec({
+ mark: "bar",
+ encoding: {
+ x: Mocks.xAxis,
+ y: Mocks.yAxis,
+ row: Mocks.rowAxis,
+ column: Mocks.columnAxis,
+ },
+ });
+ const datasource = "df";
+
+ const result = generateAltairChart(spec, datasource).toCode();
+
+ expect(result).toMatchInlineSnapshot(`
+ "alt.Chart(df)
+ .mark_bar()
+ .encode(
+ x=alt.X(field='category'),
+ y=alt.Y(field='value'),
+ row=alt.Row(field='row', axis={
+ 'title': 'Row Axis'
+ }),
+ column=alt.Column(field='column', axis={
+ 'title': 'Column Axis'
+ })
+ )"
+ `);
+ });
+
+ it("should generate a chart with resolve_scale", () => {
+ const spec = createSpec({
+ mark: "bar",
+ encoding: {
+ x: Mocks.xAxis,
+ y: Mocks.yAxis,
+ },
+ resolve: {
+ axis: {
+ x: "independent",
+ y: "shared",
+ },
+ },
+ });
+ const datasource = "df";
+
+ const result = generateAltairChart(spec, datasource).toCode();
+
+ expect(result).toMatchInlineSnapshot(`
+ "alt.Chart(df)
+ .mark_bar()
+ .encode(
+ x=alt.X(field='category'),
+ y=alt.Y(field='value')
+ )
+ .resolve_scale(
+ x='independent',
+ y='shared'
+ )"
+ `);
+ });
+
+ it("should generate a chart with properties", () => {
+ const spec = createSpec({
+ mark: "bar",
+ encoding: {
+ x: Mocks.xAxis,
+ y: Mocks.yAxis,
+ },
+ title: "Chart Title",
+ width: 600,
+ height: 400,
+ });
+ const datasource = "df";
+
+ const result = generateAltairChart(spec, datasource).toCode();
+
+ expect(result).toMatchInlineSnapshot(`
+ "alt.Chart(df)
+ .mark_bar()
+ .encode(
+ x=alt.X(field='category'),
+ y=alt.Y(field='value')
+ )
+ .properties(
+ title='Chart Title',
+ height=400,
+ width=600
+ )"
+ `);
+ });
+
+ it("should handle custom mark properties", () => {
+ const spec = createSpec({
+ mark: Mocks.marks.bar,
+ encoding: {
+ x: Mocks.xAxis,
+ y: Mocks.yAxis,
+ },
+ });
+ const datasource = "df";
+
+ const result = generateAltairChart(spec, datasource).toCode();
+
+ expect(result).toMatchInlineSnapshot(`
+ "alt.Chart(df)
+ .mark_bar(
+ opacity=0.8,
+ color='red'
+ )
+ .encode(
+ x=alt.X(field='category'),
+ y=alt.Y(field='value')
+ )"
+ `);
+ });
+
+ it("should handle complex x/y axis", () => {
+ const spec = createSpec({
+ mark: Mocks.marks.bar,
+ encoding: {
+ x: Mocks.xAxisFull,
+ y: Mocks.yAxisFull,
+ },
+ });
+ const datasource = "df";
+
+ const result = generateAltairChart(spec, datasource).toCode();
+
+ expect(result).toMatchInlineSnapshot(`
+ "alt.Chart(df)
+ .mark_bar(
+ opacity=0.8,
+ color='red'
+ )
+ .encode(
+ x=alt.X(field='category', axis={
+ 'title': 'X Axis'
+ }),
+ y=alt.Y(field='value', axis={
+ 'title': 'Y Axis'
+ })
+ )"
+ `);
+ });
+});
diff --git a/frontend/src/components/data-table/charts/__tests__/spec-snapshot.test.ts b/frontend/src/components/data-table/charts/__tests__/spec-snapshot.test.ts
index 7c3223ccc9..f70fa47ce8 100644
--- a/frontend/src/components/data-table/charts/__tests__/spec-snapshot.test.ts
+++ b/frontend/src/components/data-table/charts/__tests__/spec-snapshot.test.ts
@@ -1,12 +1,17 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { describe, it, expect } from "vitest";
-import { createVegaSpec } from "../chart-spec/spec";
-import type { z } from "zod";
-import type { ChartSchema, ChartSchemaType } from "../schemas";
+import {
+ createSpecWithoutData,
+ augmentSpecWithData,
+ X_AXIS_REQUIRED,
+ Y_AXIS_REQUIRED,
+} from "../chart-spec/spec";
+import type { ChartSchemaType } from "../schemas";
import { NONE_AGGREGATION, ChartType } from "../types";
+import type { TopLevelSpec } from "vega-lite/build/src/spec";
-describe("createVegaSpec", () => {
+describe("create vega spec", () => {
// Sample data for testing
const sampleData = [
{ category: "A", value: 10, group: "Group 1" },
@@ -17,12 +22,8 @@ describe("createVegaSpec", () => {
{ category: "C", value: 25, group: "Group 2" },
];
- // Common test parameters
- const width = 400;
- const height = 300;
-
// Helper function to create basic form values
- const createBasicFormValues = (): z.infer<typeof ChartSchema> => ({
+ const createBasicFormValues = (): ChartSchemaType => ({
general: {
title: "Test Chart",
xColumn: {
@@ -37,220 +38,46 @@ describe("createVegaSpec", () => {
},
});
- describe("Bar Chart", () => {
- it("should create a horizontal bar chart", () => {
- const formValues: ChartSchemaType = {
- ...createBasicFormValues(),
- general: {
- ...createBasicFormValues().general,
- horizontal: true,
- },
- };
-
- const spec = createVegaSpec(
- ChartType.BAR,
- sampleData,
- formValues,
- "light",
- width,
- height,
- );
-
- expect(removeUndefined(spec)).toMatchSnapshot();
- });
-
- it("should create a stacked bar chart with grouping", () => {
- const formValues: ChartSchemaType = {
- ...createBasicFormValues(),
- general: {
- ...createBasicFormValues().general,
- colorByColumn: {
- field: "group",
- type: "string" as const,
- },
- stacking: true,
- },
- };
-
- const spec = createVegaSpec(
- ChartType.BAR,
- sampleData,
- formValues,
- "light",
- width,
- height,
- );
+ it("should create and augment a spec", () => {
+ const spec = createSpecWithoutData(
+ ChartType.BAR,
+ createBasicFormValues(),
+ "light",
+ 400,
+ 300,
+ );
+ expect(spec).toMatchSnapshot();
+ expect(typeof spec !== "string").toBe(true); // Not error message
+ expect((spec as TopLevelSpec).data).toEqual({ values: [] });
- expect(removeUndefined(spec)).toMatchSnapshot();
- });
+ // Augment the spec with data
+ const augmentedSpec = augmentSpecWithData(spec as TopLevelSpec, sampleData);
+ expect(augmentedSpec.data).toEqual({ values: sampleData });
});
- it("should create a bar chart with binning", () => {
- const formValues: ChartSchemaType = {
- ...createBasicFormValues(),
- xAxis: { bin: { binned: true, step: 10 } },
- };
+ it("should return an error message if the spec is invalid", () => {
+ const formValues = createBasicFormValues();
+ formValues.general!.xColumn!.field = undefined;
- const spec = createVegaSpec(
+ const spec = createSpecWithoutData(
ChartType.BAR,
- sampleData,
formValues,
"light",
- width,
- height,
+ 400,
+ 300,
);
+ expect(spec).toEqual(X_AXIS_REQUIRED);
- expect(removeUndefined(spec)).toMatchSnapshot();
- });
-
- describe("Line Chart", () => {
- it("should create a basic line chart spec", () => {
- const formValues: ChartSchemaType = createBasicFormValues();
- const spec = createVegaSpec(
- ChartType.LINE,
- sampleData,
- formValues,
- "light",
- width,
- height,
- );
-
- expect(removeUndefined(spec)).toMatchSnapshot();
- });
- });
-
- describe("Pie Chart", () => {
- it("should create a pie chart with tooltips", () => {
- const formValues: ChartSchemaType = {
- ...createBasicFormValues(),
- general: {
- ...createBasicFormValues().general,
- },
- tooltips: {
- auto: true,
- fields: [
- { field: "category", type: "string" as const },
- { field: "value", type: "number" as const },
- ],
- },
- };
-
- const spec = createVegaSpec(
- ChartType.PIE,
- sampleData,
- formValues,
- "light",
- width,
- height,
- );
-
- expect(removeUndefined(spec)).toMatchSnapshot();
- });
- });
-
- describe("Scatter Chart", () => {
- it("should create a scatter chart with grouping", () => {
- const formValues: ChartSchemaType = {
- ...createBasicFormValues(),
- general: {
- ...createBasicFormValues().general,
- colorByColumn: {
- field: "group",
- type: "string" as const,
- },
- },
- };
-
- const spec = createVegaSpec(
- ChartType.SCATTER,
- sampleData,
- formValues,
- "light",
- width,
- height,
- );
-
- expect(removeUndefined(spec)).toMatchSnapshot();
- });
- });
-
- describe("Theme variations", () => {
- it("should create a chart with dark theme", () => {
- const formValues: ChartSchemaType = createBasicFormValues();
- const spec = createVegaSpec(
- ChartType.BAR,
- sampleData,
- formValues,
- "dark",
- width,
- height,
- );
-
- expect(removeUndefined(spec)).toMatchSnapshot();
- });
- });
-
- describe("Edge cases", () => {
- it("should handle missing xColumn field", () => {
- const formValues: ChartSchemaType = {
- ...createBasicFormValues(),
- general: {
- ...createBasicFormValues().general,
- xColumn: {
- field: undefined,
- type: "string" as const,
- },
- },
- };
-
- const spec = createVegaSpec(
- ChartType.BAR,
- sampleData,
- formValues,
- "light",
- width,
- height,
- );
-
- expect(removeUndefined(spec)).toMatchSnapshot();
- });
-
- it("should handle missing yColumn field", () => {
- const formValues: ChartSchemaType = {
- ...createBasicFormValues(),
- general: {
- ...createBasicFormValues().general,
- yColumn: {
- field: undefined,
- type: "number" as const,
- aggregate: NONE_AGGREGATION,
- },
- },
- };
-
- const spec = createVegaSpec(
- ChartType.BAR,
- sampleData,
- formValues,
- "light",
- width,
- height,
- );
-
- expect(removeUndefined(spec)).toMatchSnapshot();
- });
+ // Undefined yColumn
+ const formValues2 = createBasicFormValues();
+ formValues2.general!.yColumn!.field = undefined;
+ const spec2 = createSpecWithoutData(
+ ChartType.BAR,
+ formValues2,
+ "light",
+ 400,
+ 300,
+ );
+ expect(spec2).toEqual(Y_AXIS_REQUIRED);
});
});
-
-function removeUndefined<T>(obj: T): T {
- if (typeof obj === "object" && obj !== null && !Array.isArray(obj)) {
- const result = {} as T;
- for (const key in obj) {
- if (obj[key] !== undefined) {
- result[key] = removeUndefined(obj[key]);
- }
- }
- return result;
- }
- return obj;
-}
diff --git a/frontend/src/components/data-table/charts/__tests__/spec.test.ts b/frontend/src/components/data-table/charts/__tests__/spec.test.ts
index 14afff4a79..0caf35637a 100644
--- a/frontend/src/components/data-table/charts/__tests__/spec.test.ts
+++ b/frontend/src/components/data-table/charts/__tests__/spec.test.ts
@@ -6,6 +6,8 @@ import { AGGREGATION_FNS, ChartType, STRING_AGGREGATION_FNS } from "../types";
import { COUNT_FIELD } from "../constants";
import { NONE_AGGREGATION } from "../types";
import { getTooltips } from "../chart-spec/tooltips";
+import type { ChartSchemaType } from "../schemas";
+import type { PositionDef } from "vega-lite/build/src/channeldef";
describe("getAxisEncoding", () => {
it("should return correct encoding for COUNT_FIELD", () => {
@@ -25,7 +27,7 @@ describe("getAxisEncoding", () => {
expect(result).toEqual({
aggregate: "count",
type: "quantitative",
- bin: { bin: true, step: 10 },
+ bin: { step: 10 },
title: undefined,
stack: true,
});
@@ -188,9 +190,13 @@ describe("getAxisEncoding", () => {
describe("getTooltips", () => {
it("should return no tooltips if undefined", () => {
const result = getTooltips({
- general: {
- xColumn: { field: "x", selectedDataType: "string" },
+ formValues: {
+ general: {
+ xColumn: { field: "x", type: "string" as const },
+ },
},
+ xEncoding: { field: "x", type: "nominal" },
+ yEncoding: {},
});
expect(result).toBeUndefined();
@@ -202,25 +208,50 @@ describe("getTooltips", () => {
fields: [],
};
- const result = getTooltips({
+ const formValues: ChartSchemaType = {
general: {
- xColumn: { field: "x", selectedDataType: "string" },
- yColumn: { field: "y", selectedDataType: "number" },
+ xColumn: {
+ type: "string" as const,
+ },
+ yColumn: {
+ type: "number" as const,
+ },
+ colorByColumn: {
+ type: "integer" as const,
+ },
},
tooltips: autoTooltips,
+ xAxis: { label: "X Axis" },
+ };
+
+ const xEncoding = {
+ field: "x",
+ type: "nominal",
+ timeUnit: "year",
+ aggregate: "sum",
+ bin: { step: 10 },
+ } as PositionDef<string>;
+
+ const result = getTooltips({
+ formValues,
+ xEncoding,
+ yEncoding: { field: "y", type: "quantitative" },
});
const expected = [
{
field: "x",
format: undefined,
- timeUnit: undefined,
- title: undefined,
- aggregate: undefined,
+ timeUnit: "year",
+ title: "X Axis",
+ aggregate: "sum",
+ bin: {
+ step: 10,
+ },
},
{
field: "y",
- format: undefined,
+ format: ",.2f", // For number fields, we should use 2 decimal places
timeUnit: undefined,
title: undefined,
aggregate: undefined,
@@ -230,19 +261,17 @@ describe("getTooltips", () => {
expect(result).toEqual(expected);
const resultWithColor = getTooltips({
- general: {
- xColumn: { field: "x", selectedDataType: "string" },
- yColumn: { field: "y", selectedDataType: "number" },
- colorByColumn: { field: "color", selectedDataType: "string" },
- },
- tooltips: autoTooltips,
+ formValues,
+ xEncoding,
+ yEncoding: { field: "y", type: "quantitative" },
+ colorByEncoding: { field: "color", type: "nominal" },
});
expect(resultWithColor).toEqual([
...expected,
{
field: "color",
- format: undefined,
+ format: ",.0f", // For integer fields, we should use no decimal places
timeUnit: undefined,
title: undefined,
aggregate: undefined,
@@ -252,34 +281,113 @@ describe("getTooltips", () => {
it("should return no fields when auto is false", () => {
const result = getTooltips({
+ formValues: {
+ general: {
+ xColumn: { field: "x", type: "string" as const },
+ yColumn: { field: "y", type: "number" as const },
+ },
+ tooltips: {
+ auto: false,
+ fields: [],
+ },
+ },
+ xEncoding: { field: "x", type: "nominal" },
+ yEncoding: { field: "y", type: "quantitative" },
+ });
+
+ expect(result).toEqual([]);
+ });
+
+ it("should enhance tooltips with encoding parameters when field name matches encoding field", () => {
+ const formValues = {
general: {
- xColumn: { field: "x", selectedDataType: "string" },
- yColumn: { field: "y", selectedDataType: "number" },
+ xColumn: { type: "string" as const },
+ yColumn: { type: "number" as const },
+ colorByColumn: { type: "string" as const },
},
tooltips: {
auto: false,
- fields: [],
+ fields: [
+ { field: "category", type: "string" as const },
+ { field: "revenue", type: "number" as const },
+ { field: "region", type: "string" as const },
+ { field: "other", type: "string" as const },
+ ],
+ },
+ xAxis: { label: "Product Category" },
+ yAxis: { label: "Total Revenue" },
+ };
+
+ const result = getTooltips({
+ formValues,
+ xEncoding: {
+ field: "category",
+ type: "nominal",
+ },
+ yEncoding: {
+ field: "revenue",
+ type: "quantitative",
+ aggregate: "sum",
},
+ colorByEncoding: { field: "region", type: "nominal" },
});
- expect(result).toEqual([]);
+ expect(result).toEqual([
+ {
+ field: "category",
+ format: undefined,
+ timeUnit: undefined,
+ title: "Product Category",
+ aggregate: undefined,
+ },
+ {
+ field: "revenue",
+ format: ",.2f",
+ timeUnit: undefined,
+ title: "Total Revenue",
+ aggregate: "sum",
+ },
+ {
+ field: "region",
+ format: undefined,
+ timeUnit: undefined,
+ title: undefined,
+ aggregate: undefined,
+ },
+ {
+ field: "other",
+ },
+ ]);
});
- it("should return fields when provided", () => {
- const result = getTooltips({
+ it("should handle count aggregate with no field set", () => {
+ const formValues = {
general: {
- xColumn: { field: "x", selectedDataType: "string" },
- yColumn: { field: "y", selectedDataType: "number" },
+ xColumn: { field: "category", type: "string" as const },
+ yColumn: { field: COUNT_FIELD, type: "number" as const },
},
tooltips: {
- auto: false,
- fields: [{ field: "x", type: "string" }],
+ auto: true,
+ fields: [],
},
+ };
+
+ const result = getTooltips({
+ formValues,
+ xEncoding: { field: "category", type: "nominal" },
+ yEncoding: { aggregate: "count", type: "quantitative" },
});
expect(result).toEqual([
{
- field: "x",
+ field: "category",
+ format: undefined,
+ timeUnit: undefined,
+ title: undefined,
+ aggregate: undefined,
+ },
+ {
+ aggregate: "count",
},
]);
});
diff --git a/frontend/src/components/data-table/charts/chart-spec/altair-generator.ts b/frontend/src/components/data-table/charts/chart-spec/altair-generator.ts
new file mode 100644
index 0000000000..cf0ddb60e7
--- /dev/null
+++ b/frontend/src/components/data-table/charts/chart-spec/altair-generator.ts
@@ -0,0 +1,156 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import {
+ FunctionCall,
+ Literal,
+ type PythonCode,
+ Variable,
+ VariableDeclaration,
+} from "@/utils/python-poet/poet";
+
+import type { VegaLiteSpec } from "@/plugins/impl/vega/types";
+
+/**
+ * Generates Python code for an Altair chart.
+ */
+export function generateAltairChart(
+ spec: VegaLiteSpec,
+ datasource: string,
+): PythonCode {
+ let code = new FunctionCall("alt.Chart", [new Variable(datasource)], true);
+
+ const hasMarkProperty = "mark" in spec;
+ if (hasMarkProperty) {
+ const markType =
+ typeof spec.mark === "string" ? spec.mark : spec.mark?.type;
+
+ if (markType) {
+ let markProps: Record<string, PythonCode> = {};
+
+ if (typeof spec.mark === "object" && "type" in spec.mark) {
+ markProps = Object.fromEntries(
+ Object.entries(spec.mark)
+ .filter(([key]) => key !== "type")
+ .map(([key, value]) => [key, new Literal(value)]),
+ );
+ }
+
+ code = code.chain(`mark_${markType}`, markProps);
+ }
+ }
+
+ const hasEncodings = "encoding" in spec;
+ if (hasEncodings) {
+ const encodeArgs: Record<string, PythonCode> = {};
+ const encodings = spec.encoding;
+
+ if (encodings?.x) {
+ const kwargs = makeKwargs(encodings.x);
+ encodeArgs.x = new FunctionCall("alt.X", kwargs);
+ }
+
+ if (encodings?.y) {
+ const kwargs = makeKwargs(encodings.y);
+ encodeArgs.y = new FunctionCall("alt.Y", kwargs);
+ }
+
+ if (encodings?.color) {
+ const kwargs = makeKwargs(encodings.color);
+ encodeArgs.color = new FunctionCall("alt.Color", kwargs);
+ }
+
+ if (encodings?.theta) {
+ const kwargs = makeKwargs(encodings.theta);
+ encodeArgs.theta = new FunctionCall("alt.Theta", kwargs);
+ }
+
+ const hasRow = encodings && "row" in encodings;
+ if (hasRow && encodings.row) {
+ const kwargs = makeKwargs(encodings.row);
+ encodeArgs.row = new FunctionCall("alt.Row", kwargs);
+ }
+
+ const hasColumn = encodings && "column" in encodings;
+ if (hasColumn && encodings.column) {
+ const kwargs = makeKwargs(encodings.column);
+ encodeArgs.column = new FunctionCall("alt.Column", kwargs);
+ }
+
+ if (encodings?.tooltip) {
+ const tooltip = encodings.tooltip;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const makeTooltip = (t: Record<string, any>) => {
+ const kwargs = makeKwargs(t);
+ return new FunctionCall("alt.Tooltip", kwargs);
+ };
+
+ const tooltipArray = Array.isArray(tooltip)
+ ? new Literal(tooltip.map(makeTooltip))
+ : makeTooltip(tooltip);
+ encodeArgs.tooltip = tooltipArray;
+ }
+
+ code = code.chain("encode", encodeArgs);
+ }
+
+ if (spec.resolve) {
+ const resolve = spec.resolve;
+ const axisArgs: Record<string, PythonCode> = {};
+
+ if (resolve.axis?.x) {
+ axisArgs.x = new Literal(resolve.axis.x);
+ }
+
+ if (resolve.axis?.y) {
+ axisArgs.y = new Literal(resolve.axis.y);
+ }
+
+ code = code.chain("resolve_scale", axisArgs);
+ }
+
+ const propertiesArgs: Record<string, PythonCode> = {};
+ const propertiesKeys = ["title", "height", "width"];
+ for (const key of propertiesKeys) {
+ if (key in spec) {
+ propertiesArgs[key] = new Literal(spec[key as keyof VegaLiteSpec]);
+ }
+ }
+
+ if (Object.keys(propertiesArgs).length > 0) {
+ code = code.chain("properties", propertiesArgs);
+ }
+
+ return code;
+}
+
+/**
+ * Wraps altair code in a variable declaration.
+ *
+ * @param chartType - The type of chart to generate.
+ * @param spec - The specification of the chart.
+ * @param datasource - The name of the datasource to use.
+ * @param variableName - The name of the variable to declare.
+ */
+export function generateAltairChartSnippet(
+ spec: VegaLiteSpec,
+ datasource: string,
+ variableName: string,
+): string {
+ const code = generateAltairChart(spec, datasource).toCode();
+ return `
+${new VariableDeclaration(variableName, code).toCode()}
+${variableName}
+ `.trim();
+}
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+function makeKwargs<T extends Record<string, any>>(obj: T) {
+ const result: Record<string, PythonCode> = {};
+
+ for (const [key, value] of Object.entries(obj)) {
+ if (value !== undefined) {
+ result[key] = new Literal(value);
+ }
+ }
+
+ return result;
+}
diff --git a/frontend/src/components/data-table/charts/chart-spec/encodings.ts b/frontend/src/components/data-table/charts/chart-spec/encodings.ts
index 615c5cb947..b6eb99d4e3 100644
--- a/frontend/src/components/data-table/charts/chart-spec/encodings.ts
+++ b/frontend/src/components/data-table/charts/chart-spec/encodings.ts
@@ -1,7 +1,7 @@
/* Copyright 2024 Marimo. All rights reserved. */
import type { z } from "zod";
-import type { BinSchema, ChartSchema } from "../schemas";
+import type { BinSchema, ChartSchemaType } from "../schemas";
import {
type AggregationFn,
@@ -18,13 +18,18 @@ import type { ColorDef, OffsetDef } from "vega-lite/build/src/channeldef";
import { convertDataTypeToVega } from "./types";
import type { ColorScheme } from "vega";
import type { Aggregate } from "vega-lite/build/src/aggregate";
+import type { BinParams } from "vega-lite/build/src/bin";
+import type { Scale } from "vega-lite/build/src/scale";
export function getBinEncoding(
+ chartType: ChartType,
selectedDataType: SelectableDataType,
binValues?: z.infer<typeof BinSchema>,
- chartType?: ChartType,
-) {
+): boolean | BinParams | undefined {
if (chartType === ChartType.HEATMAP) {
+ if (!binValues?.maxbins) {
+ return undefined;
+ }
return { maxbins: binValues?.maxbins };
}
@@ -37,28 +42,42 @@ export function getBinEncoding(
return undefined;
}
- return { bin: true, step: binValues.step, maxbins: binValues.maxbins };
+ const binParams: BinParams = {};
+ if (binValues.step) {
+ binParams.step = binValues.step;
+ }
+ if (binValues.maxbins) {
+ binParams.maxbins = binValues.maxbins;
+ }
+
+ if (Object.keys(binParams).length === 0) {
+ return true;
+ }
+
+ return binParams;
}
-export function getColorInScale(formValues: z.infer<typeof ChartSchema>) {
+export function getColorInScale(
+ formValues: ChartSchemaType,
+): Scale | undefined {
const colorRange = formValues.color?.range;
if (colorRange?.length) {
return { range: colorRange };
}
const scheme = formValues.color?.scheme;
- return scheme === DEFAULT_COLOR_SCHEME
- ? undefined
- : { scheme: scheme as ColorScheme };
+ if (scheme && scheme !== DEFAULT_COLOR_SCHEME) {
+ return { scheme: scheme as ColorScheme };
+ }
}
export function getColorEncoding(
chartType: ChartType,
- formValues: z.infer<typeof ChartSchema>,
-): { color?: ColorDef<string> } | undefined {
+ formValues: ChartSchemaType,
+): ColorDef<string> | undefined {
if (
chartType === ChartType.PIE ||
- !isFieldSet(formValues.general.colorByColumn?.field)
+ !isFieldSet(formValues.general?.colorByColumn?.field)
) {
return undefined;
}
@@ -66,10 +85,8 @@ export function getColorEncoding(
const colorByColumn = formValues.general.colorByColumn;
if (colorByColumn.field === COUNT_FIELD) {
return {
- color: {
- aggregate: "count",
- type: "quantitative",
- },
+ aggregate: "count",
+ type: "quantitative",
};
}
@@ -78,29 +95,27 @@ export function getColorEncoding(
const aggregate = formValues.general.colorByColumn.aggregate;
return {
- color: {
- field: colorByColumn.field,
- type: convertDataTypeToVega(selectedDataType),
- scale: getColorInScale(formValues),
- aggregate: getAggregate(aggregate, selectedDataType),
- bin: getBinEncoding(selectedDataType, colorBin, chartType),
- },
+ field: colorByColumn.field,
+ type: convertDataTypeToVega(selectedDataType),
+ scale: getColorInScale(formValues),
+ aggregate: getAggregate(aggregate, selectedDataType),
+ bin: getBinEncoding(chartType, selectedDataType, colorBin),
};
}
export function getOffsetEncoding(
chartType: ChartType,
- formValues: z.infer<typeof ChartSchema>,
+ formValues: ChartSchemaType,
): OffsetDef<string> | undefined {
// Offset only applies to bar charts, to unstack them
if (
- formValues.general.stacking ||
- !isFieldSet(formValues.general.colorByColumn?.field) ||
+ formValues.general?.stacking ||
+ !isFieldSet(formValues.general?.colorByColumn?.field) ||
chartType !== ChartType.BAR
) {
return undefined;
}
- return { field: formValues.general.colorByColumn?.field };
+ return { field: formValues.general?.colorByColumn?.field };
}
export function getAggregate(
diff --git a/frontend/src/components/data-table/charts/chart-spec/spec.ts b/frontend/src/components/data-table/charts/chart-spec/spec.ts
index 660c95339d..9df4864755 100644
--- a/frontend/src/components/data-table/charts/chart-spec/spec.ts
+++ b/frontend/src/components/data-table/charts/chart-spec/spec.ts
@@ -2,11 +2,11 @@
import type { TopLevelSpec } from "vega-lite";
import type { ResolvedTheme } from "@/theme/useTheme";
import type {
- BinSchema,
- ChartSchema,
AxisSchema,
RowFacet,
ColumnFacet,
+ ChartSchemaType,
+ BinSchema,
} from "../schemas";
import { ChartType } from "../types";
import type { z } from "zod";
@@ -29,21 +29,22 @@ import {
} from "./encodings";
import { convertChartTypeToMark, convertDataTypeToVega } from "./types";
import { getTooltips } from "./tooltips";
+import type { Resolve } from "vega-lite/build/src/resolve";
/**
* Convert marimo chart configuration to Vega-Lite specification.
*/
export type ErrorMessage = TypedString<"ErrorMessage">;
+export const X_AXIS_REQUIRED = "X-axis column is required" as ErrorMessage;
+export const Y_AXIS_REQUIRED = "Y-axis column is required" as ErrorMessage;
-export function createVegaSpec(
+export function createSpecWithoutData(
chartType: ChartType,
- data: object[],
- formValues: z.infer<typeof ChartSchema>,
+ formValues: ChartSchemaType,
theme: ResolvedTheme,
width: number | "container",
height: number,
- // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
): TopLevelSpec | ErrorMessage {
const {
xColumn,
@@ -53,18 +54,18 @@ export function createVegaSpec(
stacking,
title,
facet,
- } = formValues.general;
+ } = formValues.general ?? {};
if (chartType === ChartType.PIE) {
- return getPieChartSpec(data, formValues, theme, width, height);
+ return getPieChartSpec([], formValues, theme, width, height);
}
// Validate required fields
if (!isFieldSet(xColumn?.field)) {
- return "X-axis column is required" as ErrorMessage;
+ return X_AXIS_REQUIRED;
}
if (!isFieldSet(yColumn?.field)) {
- return "Y-axis column is required" as ErrorMessage;
+ return Y_AXIS_REQUIRED;
}
// Determine encoding keys based on chart type
@@ -88,30 +89,44 @@ export function createVegaSpec(
chartType,
);
- const rowFacet = facet?.row.field ? getFacetEncoding(facet.row) : undefined;
+ const rowFacet = facet?.row.field
+ ? getFacetEncoding(facet.row, chartType)
+ : undefined;
const columnFacet = facet?.column.field
- ? getFacetEncoding(facet.column)
+ ? getFacetEncoding(facet.column, chartType)
: undefined;
+ const colorByEncoding = getColorEncoding(chartType, formValues);
+
// Create the final spec
return {
- ...getBaseSpec(data, formValues, theme, width, height, title),
+ ...getBaseSpec([], formValues, theme, width, height, title),
mark: { type: convertChartTypeToMark(chartType) },
encoding: {
[xEncodingKey]: horizontal ? yEncoding : xEncoding,
[yEncodingKey]: horizontal ? xEncoding : yEncoding,
xOffset: getOffsetEncoding(chartType, formValues),
- ...getColorEncoding(chartType, formValues),
- tooltip: getTooltips(formValues),
+ color: colorByEncoding,
+ tooltip: getTooltips({
+ formValues,
+ xEncoding,
+ yEncoding,
+ colorByEncoding,
+ }),
row: rowFacet,
column: columnFacet,
},
- resolve: {
- axis: {
- x: facet?.column.linkXAxis ? "shared" : "independent",
- y: facet?.row.linkYAxis ? "shared" : "independent",
- },
- },
+ ...getResolve(facet?.column, facet?.row),
+ };
+}
+
+export function augmentSpecWithData(
+ spec: TopLevelSpec,
+ data: object[],
+): TopLevelSpec {
+ return {
+ ...spec,
+ data: { values: data },
};
}
@@ -128,7 +143,7 @@ export function getAxisEncoding(
return {
aggregate: "count",
type: "quantitative",
- bin: getBinEncoding(selectedDataType, binValues, chartType),
+ bin: getBinEncoding(chartType, selectedDataType, binValues),
title: label === COUNT_FIELD ? undefined : label,
stack: stack,
};
@@ -137,7 +152,7 @@ export function getAxisEncoding(
return {
field: column.field,
type: convertDataTypeToVega(column.selectedDataType || "unknown"),
- bin: getBinEncoding(selectedDataType, binValues, chartType),
+ bin: getBinEncoding(chartType, selectedDataType, binValues),
title: label,
stack: stack,
aggregate: getAggregate(column.aggregate, selectedDataType),
@@ -147,14 +162,16 @@ export function getAxisEncoding(
export function getFacetEncoding(
facet: z.infer<typeof RowFacet> | z.infer<typeof ColumnFacet>,
+ chartType: ChartType,
): FacetFieldDef<Field, ExprRef | SignalRef> {
- let binValues = undefined;
- // Only allow binning for number data types
- if (facet.binned && facet.selectedDataType === "number") {
- binValues = {
+ const binValues = getBinEncoding(
+ chartType,
+ facet.selectedDataType || "string",
+ {
maxbins: facet.maxbins,
- };
- }
+ binned: facet.binned,
+ },
+ );
return {
field: facet.field,
@@ -167,12 +184,12 @@ export function getFacetEncoding(
function getPieChartSpec(
data: object[],
- formValues: z.infer<typeof ChartSchema>,
+ formValues: ChartSchemaType,
theme: ResolvedTheme,
width: number | "container",
height: number,
) {
- const { yColumn, colorByColumn, title } = formValues.general;
+ const { yColumn, colorByColumn, title } = formValues.general ?? {};
if (!isFieldSet(colorByColumn?.field)) {
return "Color by column is required" as ErrorMessage;
@@ -206,14 +223,19 @@ function getPieChartSpec(
encoding: {
theta: thetaEncoding,
color: colorEncoding,
- tooltip: getTooltips(formValues),
+ tooltip: getTooltips({
+ formValues,
+ xEncoding: thetaEncoding,
+ yEncoding: thetaEncoding,
+ colorByEncoding: colorEncoding,
+ }),
},
};
}
function getBaseSpec(
data: object[],
- formValues: z.infer<typeof ChartSchema>,
+ formValues: ChartSchemaType,
theme: ResolvedTheme,
width: number | "container",
height: number,
@@ -245,3 +267,23 @@ function getTimeUnit(column: z.infer<typeof AxisSchema>) {
}
return undefined;
}
+
+function getResolve(
+ columnFacet?: z.infer<typeof ColumnFacet>,
+ rowFacet?: z.infer<typeof RowFacet>,
+): { resolve: Resolve } | undefined {
+ const resolveAxis: Resolve["axis"] = {};
+
+ if (columnFacet?.linkXAxis === false) {
+ resolveAxis.x = "independent";
+ }
+
+ if (rowFacet?.linkYAxis === false) {
+ resolveAxis.y = "independent";
+ }
+
+ // If no independent axes, return undefined (shared)
+ return Object.keys(resolveAxis).length > 0
+ ? { resolve: { axis: resolveAxis } }
+ : undefined;
+}
diff --git a/frontend/src/components/data-table/charts/chart-spec/tooltips.ts b/frontend/src/components/data-table/charts/chart-spec/tooltips.ts
index ccbc0195af..464fef0065 100644
--- a/frontend/src/components/data-table/charts/chart-spec/tooltips.ts
+++ b/frontend/src/components/data-table/charts/chart-spec/tooltips.ts
@@ -1,31 +1,13 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import type { StringFieldDef } from "vega-lite/build/src/channeldef";
-import type { z } from "zod";
-import type { AxisSchema, ChartSchema } from "../schemas";
-import type { TimeUnitTooltip } from "../types";
+import type {
+ ColorDef,
+ PositionDef,
+ StringFieldDef,
+} from "vega-lite/build/src/channeldef";
+import type { ChartSchemaType } from "../schemas";
import type { DataType } from "@/core/kernel/messages";
-import type { Tooltip } from "../components/form-fields";
-import type { Aggregate } from "vega-lite/build/src/aggregate";
import { isFieldSet } from "./spec";
-import { COUNT_FIELD } from "../constants";
-import { getAggregate } from "./encodings";
-
-function getTooltipAggregate(
- field: string,
- yColumn?: z.infer<typeof AxisSchema>,
-): Aggregate | undefined {
- if (field !== yColumn?.field) {
- return undefined;
- }
-
- if (yColumn?.field === COUNT_FIELD) {
- return "count";
- }
-
- const selectedDataType = yColumn?.selectedDataType;
- return getAggregate(yColumn.aggregate, selectedDataType || "string");
-}
function getTooltipFormat(dataType: DataType): string | undefined {
switch (dataType) {
@@ -38,85 +20,143 @@ function getTooltipFormat(dataType: DataType): string | undefined {
}
}
-function getTooltipTimeUnit(
- tooltip: Tooltip,
- formValues: z.infer<typeof ChartSchema>,
-): TimeUnitTooltip | undefined {
- const xColumn = formValues.general.xColumn;
- const yColumn = formValues.general.yColumn;
- const colorByColumn = formValues.general.colorByColumn;
- const columns = [xColumn, yColumn, colorByColumn];
-
- // Check if tooltip field matches any temporal column with timeUnit
- const matchingColumn = columns.find(
- (col) =>
- tooltip.field === col?.field &&
- col?.selectedDataType === "temporal" &&
- col?.timeUnit,
- );
-
- if (matchingColumn?.timeUnit) {
- return matchingColumn.timeUnit;
- }
-
- switch (tooltip.type) {
- case "datetime":
- return "yearmonthdatehoursminutesseconds";
- case "date":
- return "yearmonthdate";
- case "time":
- return "hoursminutesseconds";
- default:
- return undefined;
- }
+interface GetTooltipParams {
+ formValues: ChartSchemaType;
+ xEncoding: PositionDef<string>;
+ yEncoding: PositionDef<string>;
+ colorByEncoding?: ColorDef<string>;
}
-export function getTooltips(formValues: z.infer<typeof ChartSchema>) {
+export function getTooltips(
+ params: GetTooltipParams,
+): Array<StringFieldDef<string>> | undefined {
+ const { formValues, xEncoding, yEncoding, colorByEncoding } = params;
+
if (!formValues.tooltips) {
return undefined;
}
- let tooltips = formValues.tooltips.fields ?? [];
+ // We need to add the same params defined in the columns to the tooltip
+ // Else, the tooltips will alter the display of the chart
+ function addTooltip(
+ encoding: PositionDef<string> | ColorDef<string>,
+ type: DataType,
+ title?: string,
+ ): StringFieldDef<string> | undefined {
+ // For count of records, there will not be a field set
+ if (
+ "aggregate" in encoding &&
+ encoding.aggregate === "count" &&
+ !isFieldSet(encoding.field)
+ ) {
+ return { aggregate: "count" };
+ }
+
+ if (encoding && "field" in encoding && isFieldSet(encoding.field)) {
+ const tooltip: StringFieldDef<string> = {
+ field: encoding.field,
+ aggregate: encoding.aggregate,
+ timeUnit: encoding.timeUnit,
+ format: getTooltipFormat(type),
+ title: title,
+ bin: encoding.bin,
+ };
+ return tooltip;
+ }
+ }
// If autoTooltips is enabled, we manually add the x, y, and color columns to the tooltips
if (formValues.tooltips.auto) {
- const newTooltips: Tooltip[] = [];
- const xColumn = formValues.general.xColumn;
- const yColumn = formValues.general.yColumn;
- const colorByColumn = formValues.general.colorByColumn;
-
- if (isFieldSet(xColumn?.field)) {
- newTooltips.push({
- field: xColumn.field,
- type: xColumn.type || "string",
- });
+ const tooltips: Array<StringFieldDef<string>> = [];
+ const xTooltip = addTooltip(
+ xEncoding,
+ formValues.general?.xColumn?.type || "string",
+ formValues.xAxis?.label,
+ );
+ if (xTooltip) {
+ tooltips.push(xTooltip);
}
- if (isFieldSet(yColumn?.field)) {
- newTooltips.push({
- field: yColumn.field,
- type: yColumn.type || "string",
- });
+ const yTooltip = addTooltip(
+ yEncoding,
+ formValues.general?.yColumn?.type || "string",
+ formValues.yAxis?.label,
+ );
+ if (yTooltip) {
+ tooltips.push(yTooltip);
}
- if (isFieldSet(colorByColumn?.field)) {
- newTooltips.push({
- field: colorByColumn.field,
- type: colorByColumn.type || "string",
- });
+ const colorTooltip = addTooltip(
+ colorByEncoding || {},
+ formValues.general?.colorByColumn?.type || "string",
+ );
+ if (colorTooltip) {
+ tooltips.push(colorTooltip);
}
- tooltips = newTooltips;
+ return tooltips;
}
- return tooltips.map((tooltip): StringFieldDef<string> => {
- const timeUnit = getTooltipTimeUnit(tooltip, formValues);
- return {
+ // Selected tooltips from the form.
+ const selectedTooltips = formValues.tooltips.fields ?? [];
+ const tooltips: Array<StringFieldDef<string>> = [];
+
+ // We need to find the matching columns for the selected tooltips if they exist
+ // Otherwise, we can add them without other parameters
+ for (const tooltip of selectedTooltips) {
+ if (
+ "field" in xEncoding &&
+ isFieldSet(xEncoding.field) &&
+ xEncoding.field === tooltip.field
+ ) {
+ const xTooltip = addTooltip(
+ xEncoding,
+ formValues.general?.xColumn?.type || "string",
+ formValues.xAxis?.label,
+ );
+ if (xTooltip) {
+ tooltips.push(xTooltip);
+ }
+ continue;
+ }
+
+ if (
+ "field" in yEncoding &&
+ isFieldSet(yEncoding.field) &&
+ yEncoding.field === tooltip.field
+ ) {
+ const yTooltip = addTooltip(
+ yEncoding,
+ formValues.general?.yColumn?.type || "string",
+ formValues.yAxis?.label,
+ );
+ if (yTooltip) {
+ tooltips.push(yTooltip);
+ }
+ continue;
+ }
+
+ if (
+ colorByEncoding &&
+ "field" in colorByEncoding &&
+ isFieldSet(colorByEncoding.field) &&
+ colorByEncoding.field === tooltip.field
+ ) {
+ const colorTooltip = addTooltip(
+ colorByEncoding,
+ formValues.general?.colorByColumn?.type || "string",
+ );
+ if (colorTooltip) {
+ tooltips.push(colorTooltip);
+ }
+ continue;
+ }
+
+ const otherTooltip: StringFieldDef<string> = {
field: tooltip.field,
- aggregate: getTooltipAggregate(tooltip.field, formValues.general.yColumn),
- format: getTooltipFormat(tooltip.type),
- timeUnit: timeUnit,
- title: timeUnit ? tooltip.field : undefined,
};
- });
+ tooltips.push(otherTooltip);
+ }
+
+ return tooltips;
}
diff --git a/frontend/src/components/data-table/charts/charts.tsx b/frontend/src/components/data-table/charts/charts.tsx
index 00d7ec8efd..4182cc21e1 100644
--- a/frontend/src/components/data-table/charts/charts.tsx
+++ b/frontend/src/components/data-table/charts/charts.tsx
@@ -2,12 +2,18 @@
import React, { useState, useMemo } from "react";
import { Button } from "@/components/ui/button";
-import { TableIcon, XIcon, DatabaseIcon, PaintRollerIcon } from "lucide-react";
+import {
+ TableIcon,
+ XIcon,
+ DatabaseIcon,
+ PaintRollerIcon,
+ CodeIcon,
+ ChartColumnIcon,
+} from "lucide-react";
import { Tabs, TabsTrigger, TabsList, TabsContent } from "@/components/ui/tabs";
-import type { z } from "zod";
import { useForm, type UseFormReturn } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
-import { ChartSchema } from "./schemas";
+import { ChartSchema, type ChartSchemaType } from "./schemas";
import { Form } from "@/components/ui/form";
import { getDefaults } from "@/components/forms/form-utils";
import { useAtom } from "jotai";
@@ -30,8 +36,12 @@ import { ChartType } from "./types";
import { HeatmapForm } from "./forms/heatmap";
import { PieForm } from "./forms/pie";
import { CommonChartForm, StyleForm } from "./forms/common-chart";
-import { TabContainer } from "./components/layouts";
+import { CodeSnippet, TabContainer } from "./components/layouts";
import { ChartFormContext } from "./context";
+import { PythonIcon } from "@/components/editor/cell/code/icons";
+import { generateAltairChartSnippet } from "./chart-spec/altair-generator";
+import { createSpecWithoutData } from "./chart-spec/spec";
+import { useTheme } from "@/theme/useTheme";
const NEW_CHART_TYPE = "bar" as ChartType;
const DEFAULT_TAB_NAME = "table" as TabName;
@@ -100,7 +110,7 @@ export const TablePanel: React.FC<TablePanelProps> = ({
const saveTabChart = (
tabName: TabName,
chartType: ChartType,
- chartConfig: z.infer<typeof ChartSchema>,
+ chartConfig: ChartSchemaType,
) => {
if (!cellId) {
return;
@@ -186,7 +196,7 @@ export const TablePanel: React.FC<TablePanelProps> = ({
{dataTable}
</TabsContent>
{tabs.map((tab, idx) => {
- const saveChart = (formValues: z.infer<typeof ChartSchema>) => {
+ const saveChart = (formValues: ChartSchemaType) => {
saveTabChart(tab.tabName, tab.chartType, formValues);
};
const saveChartType = (chartType: ChartType) => {
@@ -210,9 +220,9 @@ export const TablePanel: React.FC<TablePanelProps> = ({
};
export const ChartPanel: React.FC<{
- chartConfig: z.infer<typeof ChartSchema> | null;
+ chartConfig: ChartSchemaType | null;
chartType: ChartType;
- saveChart: (formValues: z.infer<typeof ChartSchema>) => void;
+ saveChart: (formValues: ChartSchemaType) => void;
saveChartType: (chartType: ChartType) => void;
getDataUrl?: GetDataUrl;
fieldTypes?: FieldTypesWithExternalType | null;
@@ -224,7 +234,8 @@ export const ChartPanel: React.FC<{
getDataUrl,
fieldTypes,
}) => {
- const form = useForm<z.infer<typeof ChartSchema>>({
+ const { theme } = useTheme();
+ const form = useForm<ChartSchemaType>({
defaultValues: chartConfig ?? getDefaults(ChartSchema),
resolver: zodResolver(ChartSchema),
});
@@ -263,6 +274,14 @@ export const ChartPanel: React.FC<{
return structuredClone(formValues);
}, [formValues]);
+ const specWithoutData = createSpecWithoutData(
+ selectedChartType,
+ memoizedFormValues,
+ theme,
+ "container",
+ CHART_HEIGHT,
+ );
+
// Prevent unnecessary re-renders of the chart
const memoizedChart = useMemo(() => {
if (loading) {
@@ -272,15 +291,70 @@ export const ChartPanel: React.FC<{
return <ChartErrorState error={error} />;
}
return (
- <LazyChart
- chartType={selectedChartType}
- formValues={memoizedFormValues}
- data={data}
- width="container"
- height={CHART_HEIGHT}
- />
+ <LazyChart baseSpec={specWithoutData} data={data} height={CHART_HEIGHT} />
);
- }, [loading, error, memoizedFormValues, data, selectedChartType]);
+ }, [loading, error, specWithoutData, data]);
+
+ const developmentMode = import.meta.env.DEV;
+
+ const renderChartDisplay = () => {
+ let altairCodeSnippet = "X and Y columns are not set";
+ if (typeof specWithoutData !== "string") {
+ altairCodeSnippet = generateAltairChartSnippet(
+ specWithoutData,
+ "df",
+ "_chart",
+ );
+ }
+
+ return (
+ <Tabs defaultValue="chart">
+ <TabsList>
+ <TabsTrigger value="chart" className="h-6">
+ <ChartColumnIcon className="text-muted-foreground mr-2 w-4 h-4" />
+ Chart
+ </TabsTrigger>
+ <TabsTrigger value="code" className="h-6">
+ <PythonIcon className="text-muted-foreground mr-2" />
+ Python code
+ </TabsTrigger>
+ {developmentMode && (
+ <>
+ <TabsTrigger value="formValues" className="h-6">
+ <CodeIcon className="text-muted-foreground mr-2 w-4 h-4" />
+ Form values (debug)
+ </TabsTrigger>
+ <TabsTrigger value="vegaSpec" className="h-6">
+ <CodeIcon className="text-muted-foreground mr-2 w-4 h-4" />
+ Vega spec (debug)
+ </TabsTrigger>
+ </>
+ )}
+ </TabsList>
+
+ <TabsContent value="chart">{memoizedChart}</TabsContent>
+ <TabsContent value="code">
+ <CodeSnippet code={altairCodeSnippet} language="python" />
+ </TabsContent>
+ {developmentMode && (
+ <>
+ <TabsContent value="formValues">
+ <CodeSnippet
+ code={JSON.stringify(formValues, null, 2)}
+ language="python"
+ />
+ </TabsContent>
+ <TabsContent value="vegaSpec">
+ <CodeSnippet
+ code={JSON.stringify(specWithoutData, null, 2)}
+ language="python"
+ />
+ </TabsContent>
+ </>
+ )}
+ </Tabs>
+ );
+ };
return (
<div className="flex flex-row gap-2 h-full rounded-md border pr-2">
@@ -300,7 +374,9 @@ export const ChartPanel: React.FC<{
chartType={selectedChartType}
/>
</div>
- <div className="flex-1 overflow-auto h-full w-full">{memoizedChart}</div>
+ <div className="flex-1 overflow-auto h-full w-full mt-3">
+ {renderChartDisplay()}
+ </div>
</div>
);
};
@@ -311,9 +387,9 @@ const ChartFormContainer = ({
fieldTypes,
chartType,
}: {
- form: UseFormReturn<z.infer<typeof ChartSchema>>;
+ form: UseFormReturn<ChartSchemaType>;
chartType: ChartType;
- saveChart: (formValues: z.infer<typeof ChartSchema>) => void;
+ saveChart: (formValues: ChartSchemaType) => void;
fieldTypes?: FieldTypesWithExternalType | null;
}) => {
let fields: Field[] = [];
diff --git a/frontend/src/components/data-table/charts/components/chart-items.tsx b/frontend/src/components/data-table/charts/components/chart-items.tsx
index 7ccf40c05d..9f334abde6 100644
--- a/frontend/src/components/data-table/charts/components/chart-items.tsx
+++ b/frontend/src/components/data-table/charts/components/chart-items.tsx
@@ -109,14 +109,14 @@ const ColumnSelectorWithAggregation: React.FC<{
};
export const ChartLoadingState: React.FC = () => (
- <div className="flex items-center gap-2 justify-center h-full w-full">
+ <div className="flex items-center gap-2 justify-center">
<Loader2 className="w-10 h-10 animate-spin" strokeWidth={1} />
<span>Loading chart...</span>
</div>
);
export const ChartErrorState: React.FC<{ error: Error }> = ({ error }) => (
- <div className="flex items-center justify-center h-full w-full">
+ <div className="flex items-center justify-center">
<ErrorBanner error={error} />
</div>
);
@@ -325,6 +325,7 @@ export const Facet: React.FC = () => {
<BooleanField
fieldName={linkFieldName}
label={`Link ${facet === "row" ? "Y" : "X"} Axes`}
+ defaultValue={true}
/>
</>
)}
diff --git a/frontend/src/components/data-table/charts/components/form-fields.tsx b/frontend/src/components/data-table/charts/components/form-fields.tsx
index ff3e7725e8..07b44b8aef 100644
--- a/frontend/src/components/data-table/charts/components/form-fields.tsx
+++ b/frontend/src/components/data-table/charts/components/form-fields.tsx
@@ -10,10 +10,8 @@ import {
ArrowDownWideNarrowIcon,
} from "lucide-react";
import { type Path, useFormContext, useWatch } from "react-hook-form";
-import type { z } from "zod";
import type { DataType } from "@/core/kernel/messages";
-import type { ChartSchema } from "../schemas";
import {
FormField,
@@ -63,8 +61,11 @@ import { IconWithText } from "./layouts";
import { useChartFormContext } from "../context";
import type { NumberFieldProps } from "@/components/ui/number-field";
import { convertDataTypeToSelectable } from "../chart-spec/types";
+import type { BinSchema, ChartSchema, ChartSchemaType } from "../schemas";
+import type { z } from "zod";
const CLEAR_VALUE = "__clear__";
+
export type FieldName = Path<z.infer<typeof ChartSchema>>;
export interface Field {
@@ -75,6 +76,7 @@ export interface Field {
export interface Tooltip {
field: string;
type: DataType;
+ bin?: z.infer<typeof BinSchema>;
}
export const ColumnSelector = ({
@@ -308,10 +310,12 @@ export const BooleanField = ({
fieldName,
label,
className,
+ defaultValue,
}: {
fieldName: FieldName;
label: string;
className?: string;
+ defaultValue?: boolean;
}) => {
const form = useFormContext();
return (
@@ -323,7 +327,7 @@ export const BooleanField = ({
<FormLabel>{label}</FormLabel>
<FormControl>
<Checkbox
- checked={field.value ?? false}
+ checked={field.value ?? defaultValue ?? false}
onCheckedChange={field.onChange}
className="w-4 h-4"
/>
@@ -805,7 +809,7 @@ export const SortField = ({
export const BinFields: React.FC<{
fieldName: "xAxis" | "yAxis" | "color";
}> = ({ fieldName }) => {
- const form = useFormContext<z.infer<typeof ChartSchema>>();
+ const form = useFormContext<ChartSchemaType>();
const formValues = useWatch({ control: form.control });
const isBinned = formValues[fieldName]?.bin?.binned;
diff --git a/frontend/src/components/data-table/charts/components/layouts.tsx b/frontend/src/components/data-table/charts/components/layouts.tsx
index bf87cc31d0..31214d4796 100644
--- a/frontend/src/components/data-table/charts/components/layouts.tsx
+++ b/frontend/src/components/data-table/charts/components/layouts.tsx
@@ -1,5 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
+import { ReadonlyCode } from "@/components/editor/code/readonly-python-code";
import { AccordionItem, AccordionTrigger } from "@/components/ui/accordion";
import { AccordionContent } from "@/components/ui/accordion";
import { cn } from "@/utils/cn";
@@ -81,3 +82,17 @@ export const AccordionFormContent: React.FC<{
</AccordionContent>
);
};
+
+export const CodeSnippet: React.FC<{
+ code: string;
+ language?: "python" | "sql";
+}> = ({ code, language }) => {
+ return (
+ <ReadonlyCode
+ minHeight="330px"
+ maxHeight="330px"
+ code={code}
+ language={language}
+ />
+ );
+};
diff --git a/frontend/src/components/data-table/charts/forms/common-chart.tsx b/frontend/src/components/data-table/charts/forms/common-chart.tsx
index 0e5b38cf36..08a5819b87 100644
--- a/frontend/src/components/data-table/charts/forms/common-chart.tsx
+++ b/frontend/src/components/data-table/charts/forms/common-chart.tsx
@@ -3,8 +3,6 @@
import { XAxis, YAxis, ColorByAxis, Facet } from "../components/chart-items";
import { useFormContext, useWatch } from "react-hook-form";
import { isFieldSet } from "../chart-spec/spec";
-import type { ChartSchema } from "../schemas";
-import type { z } from "zod";
import {
BooleanField,
InputField,
@@ -25,9 +23,10 @@ import {
FormSectionHorizontalRule,
} from "../components/layouts";
import { useChartFormContext } from "../context";
+import type { ChartSchemaType } from "../schemas";
export const CommonChartForm: React.FC = () => {
- const form = useFormContext<z.infer<typeof ChartSchema>>();
+ const form = useFormContext<ChartSchemaType>();
const formValues = useWatch({ control: form.control });
const yColumn = formValues.general?.yColumn;
@@ -130,7 +129,7 @@ export const StyleForm: React.FC = () => {
export const OtherOptions: React.FC = () => {
const { saveForm } = useChartFormContext();
- const form = useFormContext<z.infer<typeof ChartSchema>>();
+ const form = useFormContext<ChartSchemaType>();
const formValues = useWatch({ control: form.control });
const autoTooltips = formValues.tooltips?.auto;
diff --git a/frontend/src/components/data-table/charts/forms/heatmap.tsx b/frontend/src/components/data-table/charts/forms/heatmap.tsx
index 3de2b110cb..3cc06312a7 100644
--- a/frontend/src/components/data-table/charts/forms/heatmap.tsx
+++ b/frontend/src/components/data-table/charts/forms/heatmap.tsx
@@ -2,15 +2,14 @@
import { useFormContext, useWatch } from "react-hook-form";
import { isFieldSet } from "../chart-spec/spec";
-import type { ChartSchema } from "../schemas";
-import type { z } from "zod";
import { NumberField } from "../components/form-fields";
import { ColorByAxis, XAxis, YAxis } from "../components/chart-items";
import { OtherOptions } from "./common-chart";
import { FormSectionHorizontalRule } from "../components/layouts";
+import type { ChartSchemaType } from "../schemas";
export const HeatmapForm: React.FC = () => {
- const form = useFormContext<z.infer<typeof ChartSchema>>();
+ const form = useFormContext<ChartSchemaType>();
const formValues = useWatch({ control: form.control });
const xColumnExists = isFieldSet(formValues.general?.xColumn?.field);
diff --git a/frontend/src/components/data-table/charts/forms/pie.tsx b/frontend/src/components/data-table/charts/forms/pie.tsx
index f75f31a92c..a8dd6908eb 100644
--- a/frontend/src/components/data-table/charts/forms/pie.tsx
+++ b/frontend/src/components/data-table/charts/forms/pie.tsx
@@ -4,8 +4,6 @@ import { ColumnSelector } from "../components/form-fields";
import { FormSectionHorizontalRule, Title } from "../components/layouts";
import { useFormContext, useWatch } from "react-hook-form";
import { isFieldSet } from "../chart-spec/spec";
-import type { ChartSchema } from "../schemas";
-import type { z } from "zod";
import {
DataTypeSelect,
AggregationSelect,
@@ -15,9 +13,10 @@ import { useChartFormContext } from "../context";
import { OtherOptions } from "./common-chart";
import { convertDataTypeToSelectable } from "../chart-spec/types";
import { EMPTY_VALUE } from "../constants";
+import type { ChartSchemaType } from "../schemas";
export const PieForm: React.FC = () => {
- const form = useFormContext<z.infer<typeof ChartSchema>>();
+ const form = useFormContext<ChartSchemaType>();
const { fields } = useChartFormContext();
const formValues = useWatch({ control: form.control });
diff --git a/frontend/src/components/data-table/charts/lazy-chart.tsx b/frontend/src/components/data-table/charts/lazy-chart.tsx
index 29e59321ef..37f35b799b 100644
--- a/frontend/src/components/data-table/charts/lazy-chart.tsx
+++ b/frontend/src/components/data-table/charts/lazy-chart.tsx
@@ -1,50 +1,36 @@
/* Copyright 2024 Marimo. All rights reserved. */
import React from "react";
-import type { ChartType } from "./types";
import { useTheme } from "@/theme/useTheme";
-
-import type { z } from "zod";
-import type { ChartSchema } from "./schemas";
import type { TopLevelSpec } from "vega-lite";
import type { ErrorMessage } from "./chart-spec/spec";
import { ChartPieIcon } from "lucide-react";
-import { createVegaSpec } from "./chart-spec/spec";
+import { augmentSpecWithData } from "./chart-spec/spec";
const LazyVega = React.lazy(() =>
import("react-vega").then((m) => ({ default: m.Vega })),
);
export const LazyChart: React.FC<{
- chartType: ChartType;
- formValues: z.infer<typeof ChartSchema>;
+ baseSpec: TopLevelSpec | ErrorMessage;
data?: object[];
- width: number | "container";
height: number;
-}> = ({ chartType, formValues, data, width, height }) => {
+}> = ({ baseSpec, data, height }) => {
const { theme } = useTheme();
if (!data) {
return <div>No data</div>;
}
- const specOrMessage = createVegaSpec(
- chartType,
- data,
- formValues,
- theme,
- width,
- height,
- );
-
const renderChart = (specOrMessage: TopLevelSpec | ErrorMessage) => {
if (typeof specOrMessage === "string") {
return <ChartEmptyState>{specOrMessage}</ChartEmptyState>;
}
+ const spec = augmentSpecWithData(specOrMessage, data);
return (
<React.Suspense fallback={<LoadingChart />}>
<LazyVega
- spec={specOrMessage}
+ spec={spec}
theme={theme === "dark" ? "dark" : undefined}
height={height}
actions={{
@@ -59,8 +45,8 @@ export const LazyChart: React.FC<{
};
return (
- <div className="h-full m-auto rounded-md mt-4 w-full">
- {renderChart(specOrMessage)}
+ <div className="h-full m-auto rounded-md w-full">
+ {renderChart(baseSpec)}
</div>
);
};
@@ -71,7 +57,7 @@ const LoadingChart = () => {
const ChartEmptyState = ({ children }: { children: React.ReactNode }) => {
return (
- <div className="h-full flex flex-col items-center justify-center gap-4">
+ <div className="flex flex-col items-center justify-center gap-4 mt-14">
<ChartPieIcon className="w-10 h-10 text-muted-foreground" />
<span className="text-md font-semibold text-muted-foreground">
{children}
diff --git a/frontend/src/components/data-table/charts/schemas.ts b/frontend/src/components/data-table/charts/schemas.ts
index 813b948f56..943d7560cd 100644
--- a/frontend/src/components/data-table/charts/schemas.ts
+++ b/frontend/src/components/data-table/charts/schemas.ts
@@ -45,20 +45,22 @@ export const ColumnFacet = BaseColumnSchema.extend({
});
export const ChartSchema = z.object({
- general: z.object({
- title: z.string().optional(),
- xColumn: AxisSchema.optional(),
- yColumn: AxisSchema.optional(),
- colorByColumn: AxisSchema.optional(),
- facet: z
- .object({
- row: RowFacet,
- column: ColumnFacet,
- })
- .optional(),
- horizontal: z.boolean().optional(),
- stacking: z.boolean().optional(),
- }),
+ general: z
+ .object({
+ title: z.string().optional(),
+ xColumn: AxisSchema.optional(),
+ yColumn: AxisSchema.optional(),
+ colorByColumn: AxisSchema.optional(),
+ facet: z
+ .object({
+ row: RowFacet,
+ column: ColumnFacet,
+ })
+ .optional(),
+ horizontal: z.boolean().optional(),
+ stacking: z.boolean().optional(),
+ })
+ .optional(),
xAxis: z
.object({
label: z.string().optional(),
diff --git a/frontend/src/components/data-table/charts/storage.ts b/frontend/src/components/data-table/charts/storage.ts
index 016f87bc01..c107611937 100644
--- a/frontend/src/components/data-table/charts/storage.ts
+++ b/frontend/src/components/data-table/charts/storage.ts
@@ -4,7 +4,7 @@ import type { CellId } from "@/core/cells/ids";
import type { TypedString } from "@/utils/typed";
import { atomWithStorage } from "jotai/utils";
import { z } from "zod";
-import { ChartSchema } from "./schemas";
+import { ChartSchema, type ChartSchemaType } from "./schemas";
import { Logger } from "@/utils/Logger";
import type { ChartType } from "./types";
import { NotebookScopedLocalStorage } from "@/utils/localStorage";
@@ -16,7 +16,7 @@ export const KEY = "marimo:charts:v2";
interface TabStorage {
tabName: TabName; // unique within cell
chartType: ChartType;
- config: z.infer<typeof ChartSchema>;
+ config: ChartSchemaType;
}
type TabStorageMap = Map<CellId, TabStorage[]>;
diff --git a/frontend/src/components/data-table/charts/types.ts b/frontend/src/components/data-table/charts/types.ts
index ef31a2949d..a592b2a41f 100644
--- a/frontend/src/components/data-table/charts/types.ts
+++ b/frontend/src/components/data-table/charts/types.ts
@@ -6,6 +6,17 @@
export const SELECTABLE_DATA_TYPES = ["number", "string", "temporal"] as const;
export type SelectableDataType = (typeof SELECTABLE_DATA_TYPES)[number];
+/**
+ * Used for adding data types in Altair encoding
+ */
+export const DATA_TYPE_LETTERS: Record<SelectableDataType, string> = {
+ number: "Q",
+ string: "N",
+ temporal: "T",
+} as const;
+export type DataTypeLetter =
+ (typeof DATA_TYPE_LETTERS)[keyof typeof DATA_TYPE_LETTERS];
+
/**
* Similar to VegaLite's TimeUnit, https://vega.github.io/vega-lite/docs/timeunit.html
*/
diff --git a/frontend/src/components/editor/cell/code/icons.tsx b/frontend/src/components/editor/cell/code/icons.tsx
index 0d6fca103c..c033de3f36 100644
--- a/frontend/src/components/editor/cell/code/icons.tsx
+++ b/frontend/src/components/editor/cell/code/icons.tsx
@@ -11,6 +11,7 @@ export const PythonIcon = (props: SVGProps<SVGSVGElement>) => (
viewBox="0 0 448 512"
{...props}
>
+ <title>Python Logo</title>
<path d="M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z" />
</svg>
);
@@ -24,6 +25,7 @@ export const MarkdownIcon = (props: SVGProps<SVGSVGElement>) => (
fill="currentColor"
{...props}
>
+ <title>Markdown Icon</title>
<path d="M593.8 59.1H46.2C20.7 59.1 0 79.8 0 105.2v301.5c0 25.5 20.7 46.2 46.2 46.2h547.7c25.5 0 46.2-20.7 46.1-46.1V105.2c0-25.4-20.7-46.1-46.2-46.1zM338.5 360.6H277v-120l-61.5 76.9-61.5-76.9v120H92.3V151.4h61.5l61.5 76.9 61.5-76.9h61.5v209.2zm135.3 3.1L381.5 256H443V151.4h61.5V256H566z" />
</svg>
);
diff --git a/frontend/src/utils/python-poet/__tests__/poet.test.ts b/frontend/src/utils/python-poet/__tests__/poet.test.ts
new file mode 100644
index 0000000000..c7862c5919
--- /dev/null
+++ b/frontend/src/utils/python-poet/__tests__/poet.test.ts
@@ -0,0 +1,286 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, it, expect } from "vitest";
+import {
+ FunctionCall,
+ FunctionArg,
+ VariableDeclaration,
+ Literal,
+} from "../poet";
+
+describe("Python Poet", () => {
+ describe("Variable Declaration", () => {
+ it("should create a variable declaration", () => {
+ const declaration = new VariableDeclaration("x", "42");
+ expect(declaration.toCode()).toBe("x = 42");
+ });
+
+ it("should handle nested code objects", () => {
+ const inner = new VariableDeclaration("y", "42");
+ const declaration = new VariableDeclaration("x", inner);
+ expect(declaration.toCode()).toBe("x = y = 42");
+ });
+ });
+
+ describe("Function Call", () => {
+ it("should create a function call", () => {
+ const call = new FunctionCall("print", [
+ new FunctionArg("message", "'Hello, world!'"),
+ ]);
+ expect(call.toCode()).toBe("print(message='Hello, world!')");
+ });
+
+ it("should create a function call with a literal", () => {
+ const call = new FunctionCall("print", {
+ message: new Literal("Hello, world!"),
+ });
+ expect(call.toCode()).toBe("print(message='Hello, world!')");
+ });
+
+ it("should add arguments", () => {
+ const call = new FunctionCall("sum", [new FunctionArg("a", "1")]).addArg(
+ new FunctionArg("b", "2"),
+ );
+ expect(call.toCode()).toBe("sum(a=1, b=2)");
+ });
+
+ it("should chain method calls", () => {
+ const call = new FunctionCall("df", []).chain("head", [
+ new FunctionArg("n", "5"),
+ ]);
+ expect(call.toCode()).toBe("df().head(n=5)");
+ });
+ });
+
+ describe("Literal", () => {
+ it("should convert boolean to True/False", () => {
+ const literal = new Literal(true);
+ expect(literal.toCode()).toBe("True");
+ });
+
+ it("should convert undefined", () => {
+ const literal = new Literal(undefined);
+ expect(literal.toCode()).toBe("");
+
+ // When removeUndefined is false, undefined is converted to None
+ const literal2 = new Literal(undefined, { removeUndefined: false });
+ expect(literal2.toCode()).toBe("None");
+ });
+
+ it("should convert null to None", () => {
+ const literal = new Literal(null);
+ expect(literal.toCode()).toBe("None");
+
+ // When removeNull is true, null is converted to empty string
+ const literal2 = new Literal(null, { removeNull: true });
+ expect(literal2.toCode()).toBe("");
+ });
+
+ it("should convert empty array to empty list", () => {
+ const literal = new Literal([]);
+ expect(literal.toCode()).toBe("[]");
+ });
+
+ it("should convert array to list", () => {
+ const literal = new Literal([1, 2, 3]);
+ expect(literal.toCode()).toBe(`[
+ 1,
+ 2,
+ 3
+]`);
+ });
+
+ it("should replace null values with None", () => {
+ const literal = new Literal([1, null, 3]);
+ expect(literal.toCode()).toBe(`[
+ 1,
+ None,
+ 3
+]`);
+ });
+
+ it("should remove undefined values from list", () => {
+ const literal = new Literal([1, undefined, 3]);
+ expect(literal.toCode()).toBe(`[
+ 1,
+ 3
+]`);
+ });
+
+ it("should convert nested array to nested list", () => {
+ const literal = new Literal([1, [2, null, 3, undefined, "5"], 4]);
+ expect(literal.toCode()).toBe(`[
+ 1,
+ [
+ 2,
+ None,
+ 3,
+ '5'
+ ],
+ 4
+]`);
+ });
+
+ it("should convert empty object to empty dict", () => {
+ const literal = new Literal({});
+ expect(literal.toCode()).toBe("{}");
+ });
+
+ it("should convert object to dict", () => {
+ const literal = new Literal({ a: 1, b: 2 });
+ expect(literal.toCode()).toBe(`{
+ 'a': 1,
+ 'b': 2
+}`);
+ });
+
+ it("should convert nested object to nested dict", () => {
+ const literal = new Literal({
+ a: 1,
+ b: { c: 2, d: null, e: undefined },
+ f: [1, 2, 3],
+ });
+ expect(literal.toCode()).toBe(`{
+ 'a': 1,
+ 'b': {
+ 'c': 2,
+ 'd': None
+ },
+ 'f': [
+ 1,
+ 2,
+ 3
+ ]
+}`);
+ });
+ });
+
+ describe("Altair Charts", () => {
+ it("should create a basic bar chart", () => {
+ const chart = new FunctionCall("alt.Chart", [
+ new FunctionArg("data", "df"),
+ ])
+ .chain("mark_bar", [])
+ .chain("encode", {
+ x: new Literal("category:N"),
+ y: new Literal("value:Q"),
+ });
+
+ expect(chart.toCode()).toMatchInlineSnapshot(
+ `"alt.Chart(data=df).mark_bar().encode(x='category:N', y='value:Q')"`,
+ );
+ });
+
+ it("should create a scatter plot with color and tooltip", () => {
+ const chart = new FunctionCall(
+ "alt.Chart",
+ [new FunctionArg("data", "df")],
+ true,
+ )
+ .chain("mark_circle", [])
+ .chain("encode", [
+ new FunctionArg("x", "'x:Q'"),
+ new FunctionArg("y", "'y:Q'"),
+ new FunctionArg("color", "'category:N'"),
+ new FunctionArg("tooltip", "['category:N', 'x:Q', 'y:Q', 'size:Q']"),
+ ])
+ .chain("interactive", []);
+
+ expect(chart.toCode()).toMatchInlineSnapshot(
+ `
+ "alt.Chart(data=df)
+ .mark_circle()
+ .encode(
+ x='x:Q',
+ y='y:Q',
+ color='category:N',
+ tooltip=['category:N', 'x:Q', 'y:Q', 'size:Q']
+ )
+ .interactive()"
+ `,
+ );
+ });
+
+ it("should create a layered chart", () => {
+ const points = new FunctionCall(
+ "alt.Chart",
+ [new FunctionArg("data", "df")],
+ true,
+ )
+ .chain("mark_point", [])
+ .chain("encode", [
+ new FunctionArg("x", "'x:Q'"),
+ new FunctionArg("y", "'y:Q'"),
+ ]);
+
+ const line = new FunctionCall(
+ "alt.Chart",
+ [new FunctionArg("data", "df")],
+ true,
+ )
+ .chain("mark_line", [])
+ .chain("encode", [
+ new FunctionArg("x", "'x:Q'"),
+ new FunctionArg("y", "'y:Q'"),
+ ]);
+
+ const layered = new FunctionCall("alt.layer", [points, line], true).chain(
+ "properties",
+ [new FunctionArg("title", "'Layered Chart'")],
+ );
+
+ expect(layered.toCode()).toMatchInlineSnapshot(
+ `
+ "alt.layer(
+ alt.Chart(data=df)
+ .mark_point()
+ .encode(
+ x='x:Q',
+ y='y:Q'
+ ),
+ alt.Chart(data=df)
+ .mark_line()
+ .encode(
+ x='x:Q',
+ y='y:Q'
+ )
+ )
+ .properties(title='Layered Chart')"
+ `,
+ );
+ });
+
+ it("should create a faceted chart", () => {
+ const chart = new FunctionCall(
+ "alt.Chart",
+ [new FunctionArg("data", "df")],
+ true,
+ )
+ .chain("mark_bar", [])
+ .chain("encode", [
+ new FunctionArg("x", "'category:N'"),
+ new FunctionArg("y", "'value:Q'"),
+ new FunctionArg("color", "'category:N'"),
+ new FunctionArg("row", "'group:N'"),
+ ])
+ .chain("properties", [
+ new FunctionArg("title", "'Faceted Bar Chart'"),
+ new FunctionArg("height", "150"),
+ ]);
+
+ expect(chart.toCode()).toMatchInlineSnapshot(`
+ "alt.Chart(data=df)
+ .mark_bar()
+ .encode(
+ x='category:N',
+ y='value:Q',
+ color='category:N',
+ row='group:N'
+ )
+ .properties(
+ title='Faceted Bar Chart',
+ height=150
+ )"
+ `);
+ });
+ });
+});
diff --git a/frontend/src/utils/python-poet/poet.ts b/frontend/src/utils/python-poet/poet.ts
new file mode 100644
index 0000000000..f56ebffc15
--- /dev/null
+++ b/frontend/src/utils/python-poet/poet.ts
@@ -0,0 +1,196 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+export interface PythonCode {
+ toCode(): string;
+}
+
+const INDENT = " ";
+
+function indent(code: string): string {
+ return code
+ .split("\n")
+ .map((line) => INDENT + line)
+ .join("\n");
+}
+
+function indentList(list: PythonCode[]): string {
+ return `\n${indent(list.map(asString).join(",\n"))}\n`;
+}
+
+function asString(value: string | PythonCode): string {
+ if (typeof value === "string") {
+ return value;
+ }
+ return value.toCode();
+}
+
+export class Variable implements PythonCode {
+ constructor(public name: string) {}
+
+ toCode(): string {
+ return this.name;
+ }
+}
+
+interface LiteralOptions {
+ removeNull?: boolean;
+ removeUndefined?: boolean;
+}
+
+export class Literal implements PythonCode {
+ constructor(
+ public readonly value: unknown,
+ public readonly opts: LiteralOptions = {},
+ ) {}
+
+ static from(value: unknown, opts: LiteralOptions = {}): Literal {
+ return new Literal(value, opts);
+ }
+
+ toCode(): string {
+ const EMPTY_VALUE = "";
+ const { removeNull = false, removeUndefined = true } = this.opts;
+
+ if (this.value === undefined) {
+ if (removeUndefined) {
+ return EMPTY_VALUE;
+ }
+ return "None";
+ }
+ if (this.value === null) {
+ if (removeNull) {
+ return EMPTY_VALUE;
+ }
+ return "None";
+ }
+ if (typeof this.value === "string") {
+ return `'${this.value}'`;
+ }
+ if (typeof this.value === "boolean") {
+ return this.value ? "True" : "False";
+ }
+
+ // If a PythonCode object
+ if (typeof this.value === "object" && "toCode" in this.value) {
+ return (this.value as PythonCode).toCode();
+ }
+
+ if (Array.isArray(this.value)) {
+ if (this.value.length === 0) {
+ return "[]";
+ }
+ return `[\n${indent(
+ this.value
+ .map((item) => new Literal(item, this.opts).toCode())
+ .filter((item) => item !== EMPTY_VALUE)
+ .join(",\n"),
+ )}\n]`;
+ }
+
+ if (typeof this.value === "object") {
+ const entries = Object.entries(this.value as Record<string, unknown>);
+ if (entries.length === 0) {
+ return "{}";
+ }
+
+ const formatEntry = (entry: [string, unknown]) => {
+ const [key, value] = entry;
+ const code = new Literal(value, this.opts).toCode();
+ if (code === "") {
+ return "";
+ }
+ return `'${key}': ${code}`;
+ };
+
+ const formattedEntries = entries
+ .map(formatEntry)
+ .filter(Boolean)
+ .join(",\n");
+
+ return `{\n${indent(formattedEntries)}\n}`;
+ }
+ return String(this.value);
+ }
+}
+
+export class VariableDeclaration implements PythonCode {
+ constructor(
+ public name: string,
+ public value: string | PythonCode,
+ ) {}
+
+ toCode(): string {
+ const right = asString(this.value);
+ if (right.includes("\n")) {
+ return `${this.name} = (\n${indent(right)}\n)`;
+ }
+ return `${this.name} = ${right}`;
+ }
+}
+
+export class FunctionArg implements PythonCode {
+ constructor(
+ public name: string,
+ public value: string | PythonCode,
+ ) {}
+
+ toCode(): string {
+ return `${this.name}=${asString(this.value)}`;
+ }
+}
+
+export class FunctionCall implements PythonCode {
+ private args: PythonCode[];
+
+ constructor(
+ public name: string,
+ args: PythonCode[] | Record<string, PythonCode>,
+ public multiLine = false,
+ ) {
+ this.args = objectToArgs(args);
+ }
+
+ toCode(): string {
+ if (this.multiLine) {
+ if (this.args.length === 0) {
+ return `${this.name}()`;
+ }
+ if (this.args.length === 1) {
+ return `${this.name}(${this.args[0].toCode()})`;
+ }
+ return `${this.name}(${indentList(this.args)})`;
+ }
+ return `${this.name}(${this.args.map(asString).join(", ")})`;
+ }
+
+ addArg(...args: PythonCode[]): FunctionCall {
+ return new FunctionCall(this.name, [...this.args, ...args], this.multiLine);
+ }
+
+ chain(
+ name: string,
+ args: PythonCode[] | Record<string, PythonCode>,
+ ): FunctionCall {
+ args = objectToArgs(args);
+
+ // If the function call is multi-line, we need to add a newline to the name
+ const fullName = this.multiLine
+ ? `${this.toCode()}\n.${name}`
+ : `${this.toCode()}.${name}`;
+
+ return new FunctionCall(fullName, args, this.multiLine);
+ }
+}
+
+function objectToArgs(
+ obj: Record<string, PythonCode> | PythonCode[],
+): PythonCode[] {
+ if (Array.isArray(obj)) {
+ return obj;
+ }
+ const entries = Object.entries(obj);
+ if (entries.length === 0) {
+ return [];
+ }
+ return entries.map(([key, value]) => new FunctionArg(key, value));
+}