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 binning to charts (#4898)

Shahmir Varqhac3adfb4fffb1
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 237991115d..14afff4a79 100644
--- a/frontend/src/components/data-table/charts/__tests__/spec.test.ts
+++ b/frontend/src/components/data-table/charts/__tests__/spec.test.ts
@@ -5,6 +5,7 @@ import { getAxisEncoding } from "../chart-spec/spec";
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";
describe("getAxisEncoding", () => {
it("should return correct encoding for COUNT_FIELD", () => {
@@ -183,3 +184,103 @@ describe("getAxisEncoding", () => {
}
});
});
+
+describe("getTooltips", () => {
+ it("should return no tooltips if undefined", () => {
+ const result = getTooltips({
+ general: {
+ xColumn: { field: "x", selectedDataType: "string" },
+ },
+ });
+
+ expect(result).toBeUndefined();
+ });
+
+ it("should return tooltips for x, y and colour when auto is enabled", () => {
+ const autoTooltips = {
+ auto: true,
+ fields: [],
+ };
+
+ const result = getTooltips({
+ general: {
+ xColumn: { field: "x", selectedDataType: "string" },
+ yColumn: { field: "y", selectedDataType: "number" },
+ },
+ tooltips: autoTooltips,
+ });
+
+ const expected = [
+ {
+ field: "x",
+ format: undefined,
+ timeUnit: undefined,
+ title: undefined,
+ aggregate: undefined,
+ },
+ {
+ field: "y",
+ format: undefined,
+ timeUnit: undefined,
+ title: undefined,
+ aggregate: undefined,
+ },
+ ];
+
+ 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,
+ });
+
+ expect(resultWithColor).toEqual([
+ ...expected,
+ {
+ field: "color",
+ format: undefined,
+ timeUnit: undefined,
+ title: undefined,
+ aggregate: undefined,
+ },
+ ]);
+ });
+
+ it("should return no fields when auto is false", () => {
+ const result = getTooltips({
+ general: {
+ xColumn: { field: "x", selectedDataType: "string" },
+ yColumn: { field: "y", selectedDataType: "number" },
+ },
+ tooltips: {
+ auto: false,
+ fields: [],
+ },
+ });
+
+ expect(result).toEqual([]);
+ });
+
+ it("should return fields when provided", () => {
+ const result = getTooltips({
+ general: {
+ xColumn: { field: "x", selectedDataType: "string" },
+ yColumn: { field: "y", selectedDataType: "number" },
+ },
+ tooltips: {
+ auto: false,
+ fields: [{ field: "x", type: "string" }],
+ },
+ });
+
+ expect(result).toEqual([
+ {
+ field: "x",
+ },
+ ]);
+ });
+});
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 c53a3163b5..615c5cb947 100644
--- a/frontend/src/components/data-table/charts/chart-spec/encodings.ts
+++ b/frontend/src/components/data-table/charts/chart-spec/encodings.ts
@@ -3,14 +3,21 @@
import type { z } from "zod";
import type { BinSchema, ChartSchema } from "../schemas";
-import { ChartType, NONE_AGGREGATION, type SelectableDataType } from "../types";
+import {
+ type AggregationFn,
+ BIN_AGGREGATION,
+ ChartType,
+ NONE_AGGREGATION,
+ STRING_AGGREGATION_FNS,
+ type SelectableDataType,
+} from "../types";
-import { DEFAULT_BIN_SIZE } from "../constants";
import { isFieldSet } from "./spec";
import { COUNT_FIELD, DEFAULT_COLOR_SCHEME } from "../constants";
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";
export function getBinEncoding(
selectedDataType: SelectableDataType,
@@ -30,12 +37,7 @@ export function getBinEncoding(
return undefined;
}
- const binstep =
- binValues.step === DEFAULT_BIN_SIZE ? undefined : binValues.step;
- const binmaxbins =
- binValues.maxbins === DEFAULT_BIN_SIZE ? undefined : binValues.maxbins;
-
- return { bin: true, step: binstep, maxbins: binmaxbins };
+ return { bin: true, step: binValues.step, maxbins: binValues.maxbins };
}
export function getColorInScale(formValues: z.infer<typeof ChartSchema>) {
@@ -80,7 +82,7 @@ export function getColorEncoding(
field: colorByColumn.field,
type: convertDataTypeToVega(selectedDataType),
scale: getColorInScale(formValues),
- aggregate: aggregate === NONE_AGGREGATION ? undefined : aggregate,
+ aggregate: getAggregate(aggregate, selectedDataType),
bin: getBinEncoding(selectedDataType, colorBin, chartType),
},
};
@@ -100,3 +102,28 @@ export function getOffsetEncoding(
}
return { field: formValues.general.colorByColumn?.field };
}
+
+export function getAggregate(
+ aggregate: AggregationFn | undefined,
+ selectedDataType: SelectableDataType,
+): Aggregate | undefined {
+ // temporal data types don't support aggregation
+ if (selectedDataType === "temporal") {
+ return undefined;
+ }
+
+ if (
+ aggregate === NONE_AGGREGATION ||
+ aggregate === BIN_AGGREGATION ||
+ !aggregate
+ ) {
+ return undefined;
+ }
+
+ if (selectedDataType === "string") {
+ return STRING_AGGREGATION_FNS.includes(aggregate)
+ ? (aggregate as Aggregate)
+ : undefined;
+ }
+ return aggregate as Aggregate;
+}
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 092e4f40c3..660c95339d 100644
--- a/frontend/src/components/data-table/charts/chart-spec/spec.ts
+++ b/frontend/src/components/data-table/charts/chart-spec/spec.ts
@@ -8,13 +8,7 @@ import type {
RowFacet,
ColumnFacet,
} from "../schemas";
-import {
- type AggregationFn,
- ChartType,
- NONE_AGGREGATION,
- type SelectableDataType,
- STRING_AGGREGATION_FNS,
-} from "../types";
+import { ChartType } from "../types";
import type { z } from "zod";
import type {
ColorDef,
@@ -26,12 +20,12 @@ import type { ExprRef, SignalRef } from "vega";
import type { TypedString } from "@/utils/typed";
import { COUNT_FIELD, EMPTY_VALUE } from "../constants";
import type { FacetFieldDef } from "vega-lite/build/src/spec/facet";
-import type { Aggregate } from "vega-lite/build/src/aggregate";
import {
getBinEncoding,
getColorEncoding,
getColorInScale,
getOffsetEncoding,
+ getAggregate,
} from "./encodings";
import { convertChartTypeToMark, convertDataTypeToVega } from "./types";
import { getTooltips } from "./tooltips";
@@ -245,27 +239,6 @@ function getFieldLabel(label?: string): string | undefined {
return trimmedLabel === EMPTY_VALUE ? undefined : trimmedLabel;
}
-function getAggregate(
- aggregate: AggregationFn | undefined,
- selectedDataType: SelectableDataType,
-): Aggregate | undefined {
- // temporal data types don't support aggregation
- if (selectedDataType === "temporal") {
- return undefined;
- }
-
- if (aggregate === NONE_AGGREGATION || !aggregate) {
- return undefined;
- }
-
- if (selectedDataType === "string") {
- return STRING_AGGREGATION_FNS.includes(aggregate)
- ? (aggregate as Aggregate)
- : undefined;
- }
- return aggregate as Aggregate;
-}
-
function getTimeUnit(column: z.infer<typeof AxisSchema>) {
if (column.selectedDataType === "temporal") {
return column.timeUnit;
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 c748e4a716..ccbc0195af 100644
--- a/frontend/src/components/data-table/charts/chart-spec/tooltips.ts
+++ b/frontend/src/components/data-table/charts/chart-spec/tooltips.ts
@@ -3,12 +3,13 @@
import type { StringFieldDef } from "vega-lite/build/src/channeldef";
import type { z } from "zod";
import type { AxisSchema, ChartSchema } from "../schemas";
-import { NONE_AGGREGATION, type TimeUnitTooltip } from "../types";
+import type { TimeUnitTooltip } from "../types";
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,
@@ -22,7 +23,8 @@ function getTooltipAggregate(
return "count";
}
- return yColumn.aggregate === NONE_AGGREGATION ? undefined : yColumn.aggregate;
+ const selectedDataType = yColumn?.selectedDataType;
+ return getAggregate(yColumn.aggregate, selectedDataType || "string");
}
function getTooltipFormat(dataType: DataType): string | undefined {
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 a2c298f03a..250f5371f9 100644
--- a/frontend/src/components/data-table/charts/components/chart-items.tsx
+++ b/frontend/src/components/data-table/charts/components/chart-items.tsx
@@ -24,6 +24,7 @@ import {
BooleanField,
SortField,
NumberField,
+ BinFields,
} from "./form-fields";
import { CHART_TYPES, type ChartType } from "../types";
import React from "react";
@@ -105,8 +106,6 @@ export const XAxis: React.FC = () => {
const shouldShowXTimeUnit =
xColumnExists && selectedXDataType === "temporal" && !isXCountField;
- // const showBinFields = xColumn?.selectedDataType === "number";
-
return (
<FieldSection>
<Title text="X-Axis" />
@@ -119,6 +118,7 @@ export const XAxis: React.FC = () => {
<AggregationSelect
fieldName="general.xColumn.aggregate"
selectedDataType={selectedXDataType}
+ binFieldName="xAxis.bin.binned"
/>
)}
</div>
@@ -142,7 +142,7 @@ export const XAxis: React.FC = () => {
label="Sort"
defaultValue={formValues.general?.xColumn?.sort}
/>
- {/* {showBinFields && <BinFields fieldName="xAxis" />} */}
+ <BinFields fieldName="xAxis" />
</>
)}
</FieldSection>
@@ -172,9 +172,6 @@ export const YAxis: React.FC = () => {
const shouldShowYTimeUnit =
yColumnExists && selectedYDataType === "temporal" && !isYCountField;
- // const showBinFields =
- // yColumnExists && !isYCountField && yColumn.selectedDataType === "number";
-
return (
<FieldSection>
<Title text="Y-Axis" />
@@ -187,6 +184,7 @@ export const YAxis: React.FC = () => {
<AggregationSelect
fieldName="general.yColumn.aggregate"
selectedDataType={selectedYDataType}
+ binFieldName="yAxis.bin.binned"
/>
)}
</div>
@@ -204,7 +202,6 @@ export const YAxis: React.FC = () => {
label="Time Resolution"
/>
)}
- {/* {showBinFields && <BinFields fieldName="yAxis" />} */}
{yColumnExists && xColumnExists && (
<BooleanField fieldName="general.horizontal" label="Invert axis" />
)}
@@ -223,11 +220,6 @@ export const ColorByAxis: React.FC = () => {
selectedColorByDataType = "string";
}
- // const showBinFields =
- // formValues.general?.colorByColumn?.type &&
- // ["number", "integer"].includes(formValues.general?.colorByColumn?.type) &&
- // formValues.general?.colorByColumn?.field !== COUNT_FIELD;
-
return (
<FieldSection>
<Title text="Color by" />
@@ -239,9 +231,9 @@ export const ColorByAxis: React.FC = () => {
<AggregationSelect
fieldName="general.colorByColumn.aggregate"
selectedDataType={selectedColorByDataType}
+ binFieldName="color.bin.binned"
/>
</div>
- {/* {showBinFields && <BinFields fieldName="color" />} */}
</FieldSection>
);
};
@@ -301,6 +293,7 @@ export const Facet: React.FC = () => {
<NumberField
fieldName={`general.facet.${facet}.maxbins`}
label="Max Bins"
+ placeholder="10"
/>
</div>
)}
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 8585d6d5e6..0e4fc17085 100644
--- a/frontend/src/components/data-table/charts/components/form-fields.tsx
+++ b/frontend/src/components/data-table/charts/components/form-fields.tsx
@@ -40,7 +40,6 @@ import { Multiselect } from "@/plugins/impl/MultiselectPlugin";
import {
AGGREGATION_FNS,
- type AggregationFn,
COMBINED_TIME_UNITS,
NONE_AGGREGATION,
SELECTABLE_DATA_TYPES,
@@ -48,6 +47,7 @@ import {
SINGLE_TIME_UNITS,
SORT_TYPES,
STRING_AGGREGATION_FNS,
+ BIN_AGGREGATION,
type TimeUnit,
} from "../types";
import {
@@ -57,7 +57,6 @@ import {
EMPTY_VALUE,
SCALE_TYPE_DESCRIPTIONS,
TIME_UNIT_DESCRIPTIONS,
- DEFAULT_BIN_SIZE,
} from "../constants";
import { Slider } from "@/components/ui/slider";
import { IconWithText } from "./layouts";
@@ -290,7 +289,7 @@ export const NumberField = ({
<FormControl>
<DebouncedNumberInput
{...field}
- value={field.value ?? DEFAULT_BIN_SIZE}
+ value={field.value}
onValueChange={field.onChange}
aria-label={label}
className={cn("w-16", inputClassName)}
@@ -324,7 +323,7 @@ export const BooleanField = ({
<FormLabel>{label}</FormLabel>
<FormControl>
<Checkbox
- checked={field.value}
+ checked={field.value ?? false}
onCheckedChange={field.onChange}
className="w-4 h-4"
/>
@@ -619,25 +618,59 @@ export const DataTypeSelect = ({
);
};
-export const AggregationSelect = <T extends object>({
+export const AggregationSelect = ({
fieldName,
selectedDataType,
+ binFieldName,
}: {
- fieldName: Path<T>;
+ fieldName: FieldName;
selectedDataType: SelectableDataType;
+ binFieldName: FieldName;
}) => {
- const form = useFormContext<T>();
+ const form = useFormContext();
const availableAggregations =
selectedDataType === "string" ? STRING_AGGREGATION_FNS : AGGREGATION_FNS;
- const renderSubtitle = (agg: AggregationFn) => {
+ const renderSubtitle = (text: string) => {
+ return <span className="text-xs text-muted-foreground pr-10">{text}</span>;
+ };
+
+ const renderSelectItem = (
+ value: string,
+ Icon: React.ElementType,
+ subtitle: React.ReactNode,
+ ) => {
return (
- <span className="text-xs text-muted-foreground pr-10">
- {AGGREGATION_TYPE_DESCRIPTIONS[agg]}
- </span>
+ <SelectItem
+ key={value}
+ value={value}
+ className="flex flex-col items-start justify-center"
+ subtitle={subtitle}
+ >
+ <div className="flex items-center">
+ <Icon className="w-3 h-3 mr-2" />
+ {capitalize(value)}
+ </div>
+ </SelectItem>
);
};
+ const handleFieldChange = (
+ value: string,
+ previousValue: string,
+ onChange: (value: string) => void,
+ ) => {
+ // Special handling for binning, as this is not a valid aggregation
+ if (value === BIN_AGGREGATION) {
+ form.setValue(binFieldName, true);
+ } else if (previousValue === BIN_AGGREGATION) {
+ // Otherwise, unset the bin field
+ form.setValue(binFieldName, false);
+ }
+
+ onChange(value);
+ };
+
return (
<FormField
control={form.control}
@@ -647,8 +680,10 @@ export const AggregationSelect = <T extends object>({
<FormControl>
<Select
{...field}
- value={field.value ?? NONE_AGGREGATION}
- onValueChange={field.onChange}
+ value={(field.value ?? NONE_AGGREGATION).toString()}
+ onValueChange={(value) => {
+ handleFieldChange(value, field.value, field.onChange);
+ }}
>
<SelectTrigger variant="ghost">
<SelectValue />
@@ -658,19 +693,19 @@ export const AggregationSelect = <T extends object>({
<SelectLabel>Aggregation</SelectLabel>
{availableAggregations.map((agg) => {
const Icon = AGGREGATION_TYPE_ICON[agg];
- return (
- <SelectItem
- key={agg}
- value={agg}
- className="flex flex-col items-start justify-center"
- subtitle={renderSubtitle(agg)}
- >
- <div className="flex items-center">
- <Icon className="w-3 h-3 mr-2" />
- {capitalize(agg)}
- </div>
- </SelectItem>
+ const subtitle = renderSubtitle(
+ AGGREGATION_TYPE_DESCRIPTIONS[agg],
);
+ const selectItem = renderSelectItem(agg, Icon, subtitle);
+ if (agg === BIN_AGGREGATION) {
+ return (
+ <>
+ <SelectSeparator />
+ {selectItem}
+ </>
+ );
+ }
+ return selectItem;
})}
</SelectGroup>
</SelectContent>
@@ -774,28 +809,27 @@ export const BinFields: React.FC<{
const formValues = useWatch({ control: form.control });
const isBinned = formValues[fieldName]?.bin?.binned;
- const hasStep = formValues[fieldName]?.bin?.step !== DEFAULT_BIN_SIZE;
+ if (!isBinned) {
+ return null;
+ }
+
+ const hasStep = !Number.isNaN(formValues[fieldName]?.bin?.step);
return (
<div className="flex flex-row justify-between">
- <BooleanField fieldName={`${fieldName}.bin.binned`} label="Binned" />
- {isBinned && (
- <>
- <NumberField
- fieldName={`${fieldName}.bin.step`}
- label="Step"
- inputClassName="w-14"
- placeholder="0.5" // TODO: This doesn't work yet, we still show 0
- />
- <NumberField
- fieldName={`${fieldName}.bin.maxbins`}
- label="Maxbins"
- inputClassName="w-14"
- isDisabled={hasStep}
- placeholder="10"
- />
- </>
- )}
+ <NumberField
+ fieldName={`${fieldName}.bin.step`}
+ label="Bin step"
+ inputClassName="w-14"
+ placeholder="0.5"
+ />
+ <NumberField
+ fieldName={`${fieldName}.bin.maxbins`}
+ label="Max bins"
+ inputClassName="w-14"
+ isDisabled={hasStep}
+ placeholder="10"
+ />
</div>
);
};
diff --git a/frontend/src/components/data-table/charts/constants.ts b/frontend/src/components/data-table/charts/constants.ts
index 780626a257..953378305a 100644
--- a/frontend/src/components/data-table/charts/constants.ts
+++ b/frontend/src/components/data-table/charts/constants.ts
@@ -16,6 +16,7 @@ import {
AreaChartIcon,
ChartNoAxesColumn,
ChartColumn,
+ RulerDimensionLine,
} from "lucide-react";
import type { ColorScheme } from "vega";
import type {
@@ -27,7 +28,6 @@ import type {
export const COUNT_FIELD = "__count__";
export const DEFAULT_COLOR_SCHEME = "default";
-export const DEFAULT_BIN_SIZE = 0;
// Set a field to this to reflect that it is not set
export const EMPTY_VALUE = "";
@@ -55,6 +55,7 @@ export const AGGREGATION_TYPE_ICON: Record<AggregationFn, React.ElementType> = {
stdevp: ChartNoAxesColumn,
variance: ChartColumn,
variancep: ChartColumn,
+ bin: RulerDimensionLine,
};
export const AGGREGATION_TYPE_DESCRIPTIONS: Record<AggregationFn, string> = {
@@ -71,6 +72,7 @@ export const AGGREGATION_TYPE_DESCRIPTIONS: Record<AggregationFn, string> = {
stdevp: "Standard deviation of population",
variance: "Variance",
variancep: "Variance of population",
+ bin: "Group values into bins",
};
export const COLOR_SCHEMES: Array<ColorScheme | typeof DEFAULT_COLOR_SCHEME> = [
diff --git a/frontend/src/components/data-table/charts/forms/pie.tsx b/frontend/src/components/data-table/charts/forms/pie.tsx
index ed3abafc22..f75f31a92c 100644
--- a/frontend/src/components/data-table/charts/forms/pie.tsx
+++ b/frontend/src/components/data-table/charts/forms/pie.tsx
@@ -54,6 +54,7 @@ export const PieForm: React.FC = () => {
<AggregationSelect
fieldName="general.yColumn.aggregate"
selectedDataType={ySelectedDataType}
+ binFieldName="yAxis.bin.binned"
/>
</div>
diff --git a/frontend/src/components/data-table/charts/types.ts b/frontend/src/components/data-table/charts/types.ts
index be8009aaa5..ef31a2949d 100644
--- a/frontend/src/components/data-table/charts/types.ts
+++ b/frontend/src/components/data-table/charts/types.ts
@@ -51,6 +51,7 @@ export const SORT_TYPES = ["ascending", "descending"] as const;
export type SortType = (typeof SORT_TYPES)[number];
export const NONE_AGGREGATION = "none";
+export const BIN_AGGREGATION = "bin"; // We use this not to aggregate, but to bin
/**
* Subset of VegaLite's AggregateOp, https://vega.github.io/vega-lite/docs/aggregate.html#op
@@ -69,6 +70,7 @@ export const AGGREGATION_FNS = [
"stdevp",
"variance",
"variancep",
+ BIN_AGGREGATION,
] as const;
export type AggregationFn = (typeof AGGREGATION_FNS)[number];