Skip to content

An open source alternative to Tableau. Embeddable visual analytic

fix(observable-plot): avoid implicit scatter stacking (#522)

Elwynn Chen160c3815bac2
diff --git a/packages/graphic-walker/src/lib/observablePlot.test.ts b/packages/graphic-walker/src/lib/observablePlot.test.ts
index a86e53de..c57ccc15 100644
--- a/packages/graphic-walker/src/lib/observablePlot.test.ts
+++ b/packages/graphic-walker/src/lib/observablePlot.test.ts
@@ -2,48 +2,81 @@ jest.mock('@observablehq/plot', () => {
class MockMark {
ariaLabel: string;
channels: any;
+ data: any[];
+ options: any;
+ variant: string;
z?: string;
- constructor(name: string, opts: any = {}) {
+
+ constructor(name: string, variant: string, data: any[], opts: any = {}) {
this.ariaLabel = name;
+ this.variant = variant;
+ this.data = data;
+ this.options = opts;
this.channels = {};
- if (opts.x) this.channels.x = { value: { label: opts.x } };
- if (opts.y) {
+ if (opts.x !== undefined) this.channels.x = { value: { label: opts.x } };
+ if (opts.y !== undefined) {
this.channels.y1 = { value: { label: opts.y } };
this.channels.y2 = { value: { label: opts.y } };
}
+ if (opts.x1 !== undefined) this.channels.x1 = { value: { label: opts.x1 } };
+ if (opts.x2 !== undefined) this.channels.x2 = { value: { label: opts.x2 } };
+ if (opts.y1 !== undefined) this.channels.y1 = { value: { label: opts.y1 } };
+ if (opts.y2 !== undefined) this.channels.y2 = { value: { label: opts.y2 } };
if (opts.z) this.z = opts.z;
}
}
- const factory = (name: string) => (data: any[], opts: any = {}) => new MockMark(name, opts);
+
+ const factory = (name: string, variant: string) => (data: any[], opts: any = {}) => new MockMark(name, variant, data, opts);
+ const stackFactory = (stack: string) =>
+ jest.fn((stackOptions: any, opts: any) => ({
+ ...opts,
+ stack,
+ stackOptions,
+ }));
+
return {
- barY: factory('bar'),
- barX: factory('bar'),
- lineY: factory('line'),
- lineX: factory('line'),
- dot: factory('dot'),
- text: factory('text'),
- areaY: factory('area'),
- areaX: factory('area'),
- tickX: factory('tick'),
- tickY: factory('tick'),
- rectX: factory('rect'),
- rectY: factory('rect'),
- ruleX: factory('rule'),
- ruleY: factory('rule'),
- boxX: factory('box'),
- boxY: factory('box'),
- stackY: () => (opts: any) => ({ ...opts, stack: 'y' }),
- stackX: () => (opts: any) => ({ ...opts, stack: 'x' }),
+ barY: factory('bar', 'barY'),
+ barX: factory('bar', 'barX'),
+ lineY: factory('line', 'lineY'),
+ lineX: factory('line', 'lineX'),
+ dot: factory('dot', 'dot'),
+ text: factory('text', 'text'),
+ areaY: factory('area', 'areaY'),
+ areaX: factory('area', 'areaX'),
+ tickX: factory('tick', 'tickX'),
+ tickY: factory('tick', 'tickY'),
+ rectX: factory('rect', 'rectX'),
+ rectY: factory('rect', 'rectY'),
+ ruleX: factory('rule', 'ruleX'),
+ ruleY: factory('rule', 'ruleY'),
+ boxX: factory('box', 'boxX'),
+ boxY: factory('box', 'boxY'),
+ stackY: stackFactory('y'),
+ stackX: stackFactory('x'),
+ stackY2: stackFactory('y2'),
+ stackX2: stackFactory('x2'),
};
});
+import * as Plot from '@observablehq/plot';
import { __test__vegaLiteToPlot } from './observablePlot';
+const expectNoStack = () => {
+ expect(Plot.stackX).not.toHaveBeenCalled();
+ expect(Plot.stackY).not.toHaveBeenCalled();
+ expect(Plot.stackX2).not.toHaveBeenCalled();
+ expect(Plot.stackY2).not.toHaveBeenCalled();
+};
+
describe('vegaLiteToPlot', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
test('bar chart basic', () => {
const vlSpec = {
mark: 'bar',
- data: { values: [ { a: 'A', b: 1 }, { a: 'B', b: 2 } ] },
+ data: { values: [{ a: 'A', b: 1 }, { a: 'B', b: 2 }] },
encoding: {
x: { field: 'a', type: 'nominal' },
y: { field: 'b', type: 'quantitative' },
@@ -52,16 +85,17 @@ describe('vegaLiteToPlot', () => {
const plot = __test__vegaLiteToPlot(vlSpec);
const mark = plot.marks[0];
expect(mark.ariaLabel).toBe('bar');
+ expect(mark.variant).toBe('barY');
expect(mark.channels.x.value.label).toBe('a');
expect(mark.channels.y1.value.label).toBe('b');
expect(plot.x.type).toBeUndefined();
expect(plot.y.type).toBeUndefined();
});
- test('line chart with color', () => {
+ test('line chart with color stays unstacked and grouped', () => {
const vlSpec = {
mark: 'line',
- data: { values: [ { t: '2024-01-01', v: 1, c: 'A' }, { t: '2024-01-02', v: 2, c: 'B' } ] },
+ data: { values: [{ t: '2024-01-01', v: 1, c: 'A' }, { t: '2024-01-02', v: 2, c: 'B' }] },
encoding: {
x: { field: 't', type: 'temporal' },
y: { field: 'v', type: 'quantitative' },
@@ -71,13 +105,15 @@ describe('vegaLiteToPlot', () => {
const plot = __test__vegaLiteToPlot(vlSpec);
const mark = plot.marks[0];
expect(mark.ariaLabel).toBe('line');
+ expect(mark.options.z).toBe('c');
+ expectNoStack();
expect(plot.x.type).toBe('utc');
});
test('temporal bar chart uses band scale', () => {
const vlSpec = {
mark: 'bar',
- data: { values: [ { t: '2024-01-01', v: 1 }, { t: '2024-01-02', v: 2 } ] },
+ data: { values: [{ t: '2024-01-01', v: 1 }, { t: '2024-01-02', v: 2 }] },
encoding: {
x: { field: 't', type: 'temporal' },
y: { field: 'v', type: 'quantitative' },
@@ -87,4 +123,316 @@ describe('vegaLiteToPlot', () => {
expect(plot.x.type).toBe('band');
expect(plot.marks[0].ariaLabel).toBe('bar');
});
+
+ test('point chart with color is not implicitly stacked', () => {
+ const vlSpec = {
+ mark: 'point',
+ data: {
+ values: [
+ { x: 1, y: 10, c: 'A' },
+ { x: 2, y: 20, c: 'B' },
+ ],
+ },
+ encoding: {
+ x: { field: 'x', type: 'quantitative' },
+ y: { field: 'y', type: 'quantitative' },
+ color: { field: 'c', type: 'nominal' },
+ },
+ };
+
+ const plot = __test__vegaLiteToPlot(vlSpec);
+ const mark = plot.marks[0];
+
+ expect(mark.ariaLabel).toBe('dot');
+ expect(mark.options).toMatchObject({ x: 'x', y: 'y', stroke: 'c' });
+ expectNoStack();
+ });
+
+ test('point chart with color respects explicit stack null', () => {
+ const plot = __test__vegaLiteToPlot({
+ mark: 'point',
+ data: { values: [{ x: 1, y: 10, c: 'A' }] },
+ encoding: {
+ x: { field: 'x', type: 'quantitative', stack: null },
+ y: { field: 'y', type: 'quantitative', stack: null },
+ color: { field: 'c', type: 'nominal' },
+ },
+ });
+
+ expect(plot.marks[0].options).toMatchObject({ x: 'x', y: 'y', stroke: 'c' });
+ expectNoStack();
+ });
+
+ test('point chart uses x stack precedence and the upper endpoint', () => {
+ const plot = __test__vegaLiteToPlot({
+ mark: 'point',
+ data: { values: [{ x: 1, y: 10, c: 'A' }] },
+ encoding: {
+ x: { field: 'x', type: 'quantitative', stack: 'normalize' },
+ y: { field: 'y', type: 'quantitative', stack: 'normalize' },
+ color: { field: 'c', type: 'nominal' },
+ },
+ });
+ const mark = plot.marks[0];
+
+ expect(Plot.stackX2).toHaveBeenCalledWith({ offset: 'normalize' }, expect.objectContaining({ x: 'x', y: 'y', z: 'c' }));
+ expect(Plot.stackY2).not.toHaveBeenCalled();
+ expect(mark.options).toMatchObject({ stack: 'x2', stackOptions: { offset: 'normalize' }, z: 'c' });
+ });
+
+ test.each(['normalize', 'center'])('point chart ignores explicit %s stacking without a color group', (stack) => {
+ const plot = __test__vegaLiteToPlot({
+ mark: 'point',
+ data: { values: [{ x: 1, y: 10 }] },
+ encoding: {
+ x: { field: 'x', type: 'quantitative', stack },
+ y: { field: 'y', type: 'quantitative', stack },
+ },
+ });
+
+ expectNoStack();
+ expect(plot.marks[0].options).toMatchObject({ x: 'x', y: 'y' });
+ });
+
+ test('real binned x encoding is excluded from stack-axis selection', () => {
+ const plot = __test__vegaLiteToPlot({
+ mark: 'bar',
+ data: { values: [{ 'x[0]': 0, 'x[1]': 10, y: 2, c: 'A' }] },
+ encoding: {
+ x: { field: 'x[0]', bin: { binned: true } },
+ x2: { field: 'x[1]' },
+ y: { field: 'y', type: 'quantitative', stack: 'normalize' },
+ color: { field: 'c', type: 'nominal' },
+ },
+ });
+
+ expect(Plot.stackY).toHaveBeenCalledWith({ offset: 'normalize' }, expect.objectContaining({ y: 'y', z: 'c' }));
+ expect(Plot.stackX).not.toHaveBeenCalled();
+ expect(plot.marks[0].variant).toBe('barY');
+ });
+
+ test('explicitly stacked line uses the upper endpoint', () => {
+ const plot = __test__vegaLiteToPlot({
+ mark: 'line',
+ data: { values: [{ t: '2024-01-01', v: 1, c: 'A' }] },
+ encoding: {
+ x: { field: 't', type: 'temporal' },
+ y: { field: 'v', type: 'quantitative', stack: 'normalize' },
+ color: { field: 'c', type: 'nominal' },
+ },
+ });
+
+ expect(Plot.stackY2).toHaveBeenCalledWith({ offset: 'normalize' }, expect.objectContaining({ y: 'v', z: 'c' }));
+ expect(plot.marks[0].options).toMatchObject({ stack: 'y2', stackOptions: { offset: 'normalize' } });
+ });
+
+ test('colored bar keeps Vega-Lite default stacking and color grouping', () => {
+ const plot = __test__vegaLiteToPlot({
+ mark: 'bar',
+ data: { values: [{ x: 'A', y: 1, c: 'one' }, { x: 'A', y: 2, c: 'two' }] },
+ encoding: {
+ x: { field: 'x', type: 'nominal' },
+ y: { field: 'y', type: 'quantitative' },
+ color: { field: 'c', type: 'nominal' },
+ },
+ });
+
+ expect(Plot.stackY).toHaveBeenCalledWith({}, expect.objectContaining({ y: 'y', z: 'c' }));
+ expect(plot.marks[0].options).toMatchObject({ stack: 'y', stackOptions: {}, z: 'c' });
+ });
+
+ test.each(['bar', 'area'])('%s defaults to a y stack when both axes are quantitative', (markType) => {
+ const plot = __test__vegaLiteToPlot({
+ mark: markType,
+ data: { values: [{ x: 1, y: 2, c: 'A' }] },
+ encoding: {
+ x: { field: 'x', type: 'quantitative' },
+ y: { field: 'y', type: 'quantitative' },
+ color: { field: 'c', type: 'nominal' },
+ },
+ });
+
+ expect(Plot.stackY).toHaveBeenCalledWith({}, expect.objectContaining({ x: 'x', y: 'y', z: 'c' }));
+ expect(plot.marks[0].variant).toBe(`${markType}Y`);
+ });
+
+ test('zero stack mode does not pass an unsupported Plot offset', () => {
+ const plot = __test__vegaLiteToPlot({
+ mark: 'bar',
+ data: { values: [{ x: 'A', y: 1, c: 'one' }] },
+ encoding: {
+ x: { field: 'x', type: 'nominal' },
+ y: { field: 'y', type: 'quantitative', stack: 'zero' },
+ color: { field: 'c', type: 'nominal' },
+ },
+ });
+
+ expect(Plot.stackY).toHaveBeenCalledWith({}, expect.anything());
+ expect(plot.marks[0].options.stackOptions).toEqual({});
+ });
+
+ test.each(['normalize', 'center'])('aggregated bar ignores explicit %s stacking without a color group', (stack) => {
+ const plot = __test__vegaLiteToPlot({
+ mark: 'bar',
+ data: { values: [{ x: 'A', y: 1 }] },
+ encoding: {
+ x: { field: 'x', type: 'nominal' },
+ y: { field: 'y', type: 'quantitative', aggregate: 'sum', stack },
+ },
+ });
+ const mark = plot.marks[0];
+
+ expectNoStack();
+ expect(mark.options).toMatchObject({ y1: 0, y2: 'y' });
+ expect(mark.options.y).toBeUndefined();
+ });
+
+ test.each([true, false])('bar stack null suppresses Plot implicit stacking (color: %s)', (withColor) => {
+ const color = withColor ? { color: { field: 'c', type: 'nominal' } } : {};
+ const plot = __test__vegaLiteToPlot({
+ mark: 'bar',
+ data: { values: [{ x: 'A', y: 1, c: 'one' }, { x: 'A', y: 2, c: 'two' }] },
+ encoding: {
+ x: { field: 'x', type: 'nominal' },
+ y: { field: 'y', type: 'quantitative', stack: null },
+ ...color,
+ },
+ });
+ const mark = plot.marks[0];
+
+ expectNoStack();
+ expect(mark.options.y).toBeUndefined();
+ expect(mark.options).toMatchObject({ y1: 0, y2: 'y' });
+ });
+
+ test('area stack null is layered and keeps color grouping', () => {
+ const plot = __test__vegaLiteToPlot({
+ mark: 'area',
+ data: { values: [{ x: 'A', y: 1, c: 'one' }] },
+ encoding: {
+ x: { field: 'x', type: 'nominal' },
+ y: { field: 'y', type: 'quantitative', stack: null },
+ color: { field: 'c', type: 'nominal' },
+ },
+ });
+ const mark = plot.marks[0];
+
+ expectNoStack();
+ expect(mark.options).toMatchObject({ y1: 0, y2: 'y', z: 'c' });
+ expect(mark.options.y).toBeUndefined();
+ });
+
+ test('horizontal bar uses an x stack', () => {
+ const plot = __test__vegaLiteToPlot({
+ mark: 'bar',
+ data: { values: [{ x: 1, y: 'A', c: 'one' }] },
+ encoding: {
+ x: { field: 'x', type: 'quantitative' },
+ y: { field: 'y', type: 'nominal' },
+ color: { field: 'c', type: 'nominal' },
+ },
+ });
+
+ expect(Plot.stackX).toHaveBeenCalledWith({}, expect.objectContaining({ x: 'x', y: 'y', z: 'c' }));
+ expect(plot.marks[0].variant).toBe('barX');
+ });
+
+ test('both-quantitative normalized bar follows the resolved x axis', () => {
+ const plot = __test__vegaLiteToPlot({
+ mark: 'bar',
+ data: { values: [{ x: 1, y: 2, c: 'A' }] },
+ encoding: {
+ x: { field: 'x', type: 'quantitative', stack: 'normalize' },
+ y: { field: 'y', type: 'quantitative', stack: 'normalize' },
+ color: { field: 'c', type: 'nominal' },
+ },
+ });
+
+ expect(Plot.stackX).toHaveBeenCalledWith({ offset: 'normalize' }, expect.objectContaining({ x: 'x', y: 'y', z: 'c' }));
+ expect(Plot.stackY).not.toHaveBeenCalled();
+ expect(plot.marks[0].variant).toBe('barX');
+ });
+
+ test.each([undefined, null, 'normalize'])('rect remains unstacked for stack %s', (stack) => {
+ const y = { field: 'y', type: 'quantitative' } as any;
+ if (stack !== undefined) y.stack = stack;
+ const plot = __test__vegaLiteToPlot({
+ mark: 'rect',
+ data: { values: [{ x: 'A', y: 1, c: 'one' }] },
+ encoding: {
+ x: { field: 'x', type: 'nominal' },
+ y,
+ color: { field: 'c', type: 'nominal' },
+ },
+ });
+ const mark = plot.marks[0];
+
+ expectNoStack();
+ expect(mark.options).toMatchObject({ y1: 0, y2: 'y' });
+ expect(mark.options.y).toBeUndefined();
+ });
+
+ test('nominal rect is left unchanged when there is no quantitative stack axis', () => {
+ const plot = __test__vegaLiteToPlot({
+ mark: 'rect',
+ data: { values: [{ x: 'A', y: 'B' }] },
+ encoding: {
+ x: { field: 'x', type: 'nominal' },
+ y: { field: 'y', type: 'nominal', stack: null },
+ },
+ });
+ const mark = plot.marks[0];
+
+ expectNoStack();
+ expect(mark.options).toMatchObject({ x: 'x', y: 'y' });
+ expect(mark.options.y1).toBeUndefined();
+ expect(mark.options.y2).toBeUndefined();
+ });
+
+ test('rule remains outside the explicitly supported stack marks', () => {
+ const plot = __test__vegaLiteToPlot({
+ mark: 'rule',
+ data: { values: [{ x: 'A', y: 1 }] },
+ encoding: {
+ x: { field: 'x', type: 'nominal' },
+ y: { field: 'y', type: 'quantitative', stack: 'normalize' },
+ },
+ });
+
+ expectNoStack();
+ expect(plot.marks[0].variant).toBe('ruleY');
+ });
+
+ test('trail ignores explicit stack and remains the existing dot fallback', () => {
+ const plot = __test__vegaLiteToPlot({
+ mark: 'trail',
+ data: { values: [{ x: 'A', y: 1 }] },
+ encoding: {
+ x: { field: 'x', type: 'nominal' },
+ y: { field: 'y', type: 'quantitative', stack: 'normalize' },
+ },
+ });
+
+ expectNoStack();
+ expect(plot.marks[0].ariaLabel).toBe('dot');
+ });
+
+ test.each(['point', 'bar'])('%s ignores invalid literal stack mode', (markType) => {
+ const plot = __test__vegaLiteToPlot({
+ mark: markType,
+ data: { values: [{ x: 'A', y: 1, c: 'one' }] },
+ encoding: {
+ x: { field: 'x', type: 'nominal' },
+ y: { field: 'y', type: 'quantitative', stack: 'stack' },
+ color: { field: 'c', type: 'nominal' },
+ },
+ });
+
+ expectNoStack();
+ if (markType === 'bar') {
+ expect(plot.marks[0].options).toMatchObject({ y1: 0, y2: 'y' });
+ } else {
+ expect(plot.marks[0].options).toMatchObject({ y: 'y' });
+ }
+ });
});
diff --git a/packages/graphic-walker/src/lib/observablePlot.ts b/packages/graphic-walker/src/lib/observablePlot.ts
index 82426f81..8ae76426 100644
--- a/packages/graphic-walker/src/lib/observablePlot.ts
+++ b/packages/graphic-walker/src/lib/observablePlot.ts
@@ -46,7 +46,7 @@ function vegaLiteToPlot(spec: any): any {
// etc. shape, opacity, text, etc. if present
// Helper function to determine mark direction based on axis types
- const getMarkDirection = (markType: string, enc: any) => {
+ const getMarkDirection = (markType: string, enc: any, preferredAxis?: 'X' | 'Y') => {
const xIsQuantitative = enc.x?.type === 'quantitative';
const yIsQuantitative = enc.y?.type === 'quantitative';
const xIsTemporal = enc.x?.type === 'temporal';
@@ -64,6 +64,9 @@ function vegaLiteToPlot(spec: any): any {
};
if (directionalMarks[markType]) {
+ if (preferredAxis) {
+ return { markFunction: directionalMarks[markType][preferredAxis], stackAxis: preferredAxis };
+ }
// If X is quantitative and Y is not quantitative (temporal, ordinal, nominal), use X-direction mark
if (xIsQuantitative && !yIsQuantitative) {
console.log(`Using X-direction mark for ${markType}: X is quantitative (${enc.x?.type}), Y is ${enc.y?.type}`);
@@ -94,7 +97,7 @@ function vegaLiteToPlot(spec: any): any {
return {
markFunction: nonDirectionalMarks[markType] || Plot.dot,
- stackAxis: 'Y' as const
+ stackAxis: preferredAxis || ('Y' as const),
};
};
@@ -152,11 +155,7 @@ function vegaLiteToPlot(spec: any): any {
};
// Helper function to create stack configuration
- const createStackConfig = (stackMode: string | null, baseConfig: any) => {
- if (!stacked || !colorField) {
- return baseConfig;
- }
-
+ const createStackConfig = (stackMode: string | null) => {
const stackOptions: any = {};
if (stackMode === "normalize") {
stackOptions.offset = "normalize";
@@ -169,12 +168,8 @@ function vegaLiteToPlot(spec: any): any {
return stackOptions;
};
- // Helper function to apply stacking to any mark
- const applyStacking = (markFunction: any, data: any[], baseConfig: any, stackAxis: 'X' | 'Y') => {
- if (!stacked || !colorField) {
- return markFunction(data, baseConfig);
- }
-
+ // Helper function to apply stacking to a supported mark
+ const applyStacking = (markType: string, markFunction: any, data: any[], baseConfig: any, stackAxis: 'X' | 'Y', stackMode: string | null) => {
// Sort data for consistent stacking based on which axis we're stacking along
const sortedData = [...data].sort((a, b) => {
// For X-direction stacking (stackAxis === 'X'), sort by Y field first (usually temporal)
@@ -198,11 +193,15 @@ function vegaLiteToPlot(spec: any): any {
if (primaryCompare !== 0) return primaryCompare;
// Secondary sort by color field for consistent stacking order
- return colorField && a[colorField] < b[colorField] ? -1 : 1;
+ if (!colorField) return 0;
+ if (a[colorField] < b[colorField]) return -1;
+ if (a[colorField] > b[colorField]) return 1;
+ return 0;
});
- const stackOptions = createStackConfig(stackMode, baseConfig);
- const stackFunction = stackAxis === 'X' ? Plot.stackX : Plot.stackY;
+ const stackOptions = createStackConfig(stackMode);
+ const rangedMark = markType === 'bar' || markType === 'area';
+ const stackFunction = stackAxis === 'X' ? (rangedMark ? Plot.stackX : Plot.stackX2) : rangedMark ? Plot.stackY : Plot.stackY2;
// Ensure z channel is set for grouping
const configWithZ = {
@@ -221,61 +220,81 @@ function vegaLiteToPlot(spec: any): any {
return markFunction(sortedData, stackFunction(stackOptions, configWithZ));
};
- // 4) Check for stacking in encoding channels (not just transforms)
- let stacked = false;
- let stackMode = null; // Can be "normalize", "center", etc.
-
- // Check if any quantitative encoding has stack property that's not null/false
- if (enc.x?.stack !== null && enc.x?.stack !== false && enc.x?.type === 'quantitative') {
- stacked = true;
- stackMode = enc.x.stack;
- }
- if (enc.y?.stack !== null && enc.y?.stack !== false && enc.y?.type === 'quantitative') {
- stacked = true;
- stackMode = enc.y.stack;
- }
- if (enc.theta?.stack !== null && enc.theta?.stack !== false && enc.theta?.type === 'quantitative') {
- stacked = true;
- stackMode = enc.theta.stack;
- }
- if (enc.radius?.stack !== null && enc.radius?.stack !== false && enc.radius?.type === 'quantitative') {
- stacked = true;
- stackMode = enc.radius.stack;
- }
-
- // Also check transforms for legacy support
- if (Array.isArray(spec.transform)) {
- for (const t of spec.transform) {
- if (t.stack) {
- // E.g. "stack": "area"
- stacked = true;
+ // 4) Resolve Vega-Lite's mark-aware stack semantics.
+ const resolveStack = (markType: string, enc: any, defaultAxis: 'X' | 'Y') => {
+ const explicitlyStackableMarks = new Set(['bar', 'area', 'point', 'circle', 'dot', 'line', 'text', 'tick']);
+ const defaultStackMarks = new Set(['bar', 'area']);
+ const channels = [
+ { axis: 'X' as const, encoding: enc.x },
+ { axis: 'Y' as const, encoding: enc.y },
+ ].filter(({ encoding }) => encoding?.type === 'quantitative' && !encoding.bin);
+ const hasExplicitStack = channels.some(({ encoding }) => encoding.stack !== undefined);
+ const explicitChannel = channels.find(({ encoding }) => Boolean(encoding.stack));
+
+ if (hasExplicitStack) {
+ const mode = explicitChannel?.encoding.stack;
+ const enabled = mode === true || mode === 'zero' || mode === 'normalize' || mode === 'center';
+ // Graphic Walker expresses stack series through color. Without one, Plot would
+ // normalize each pre-aggregated datum to 100% (or center it around zero).
+ const hasRequiredGroup = (mode !== 'normalize' && mode !== 'center') || Boolean(enc.color?.field);
+ if (enabled && hasRequiredGroup && explicitChannel && explicitlyStackableMarks.has(markType)) {
+ return {
+ stacked: true,
+ axis: explicitChannel.axis,
+ mode: mode === 'normalize' || mode === 'center' ? mode : null,
+ };
}
- // if t.aggregate => we might build a group transform
- // if t.bin => we might build a bin transform
- // etc...
+ return { stacked: false, axis: defaultAxis, mode: null };
}
- }
+
+ if (defaultStackMarks.has(markType) && channels.length > 0) {
+ return {
+ stacked: true,
+ axis: channels.length === 1 ? channels[0].axis : ('Y' as const),
+ mode: null,
+ };
+ }
+
+ return { stacked: false, axis: defaultAxis, mode: null };
+ };
+
+ const suppressImplicitStack = (markType: string, enc: any, baseConfig: any, stackAxis: 'X' | 'Y') => {
+ if (!['bar', 'area', 'rect'].includes(markType)) return baseConfig;
+
+ const axis = stackAxis === 'X' ? 'x' : 'y';
+ if (enc[axis]?.type !== 'quantitative') return baseConfig;
+
+ const value = baseConfig[axis];
+ const config = { ...baseConfig };
+ delete config[axis];
+ if (stackAxis === 'X') {
+ config.x1 = 0;
+ config.x2 = value;
+ } else {
+ config.y1 = 0;
+ config.y2 = value;
+ }
+ return config;
+ };
// Universal mark creation function
const createMark = (markType: string, data: any[], enc: any, fields: any) => {
const { colorField } = fields;
- // Get the appropriate mark function and stack axis
- const { markFunction, stackAxis } = getMarkDirection(markType, enc);
+ // Resolve stacking before choosing the directional mark so explicit X stacks use X marks.
+ const defaultDirection = getMarkDirection(markType, enc);
+ const stack = resolveStack(markType, enc, defaultDirection.stackAxis);
+ const { markFunction, stackAxis } = getMarkDirection(markType, enc, stack.stacked ? stack.axis : undefined);
// Create base configuration
const baseConfig = createBaseConfig(markType, enc, fields);
-
- // Determine if we should stack and how
- // For area charts, if there's a color field and no explicit stack=false, we should stack
- const shouldStack = stacked || (colorField && ['bar', 'area'].includes(markType) && stacked !== false);
+ const unstackedConfig = stack.stacked ? baseConfig : suppressImplicitStack(markType, enc, baseConfig, stackAxis);
console.log(`Creating ${markType} mark:`, {
markFunction: markFunction.name,
stackAxis,
- shouldStack,
- stacked,
- stackMode,
+ stacked: stack.stacked,
+ stackMode: stack.mode,
colorField,
hasColorField: !!colorField,
isStackableMarkType: ['bar', 'area'].includes(markType),
@@ -283,9 +302,9 @@ function vegaLiteToPlot(spec: any): any {
yType: enc.y?.type
});
- if (shouldStack && colorField) {
+ if (stack.stacked) {
// Apply stacking
- return applyStacking(markFunction, data, baseConfig, stackAxis);
+ return applyStacking(markType, markFunction, data, baseConfig, stackAxis, stack.mode);
} else if (colorField && ['line', 'area'].includes(markType)) {
// For multi-series line/area charts without stacking, add z channel for grouping
// and ensure proper data sorting for line charts
@@ -331,7 +350,7 @@ function vegaLiteToPlot(spec: any): any {
if (xIsQuantitative && yIsTemporal) {
console.log('Special case: X quantitative, Y temporal - using curve: "linear" for better connection');
const configWithZ = {
- ...baseConfig,
+ ...unstackedConfig,
z: colorField || undefined,
curve: "linear" // Ensure linear interpolation
};
@@ -340,13 +359,13 @@ function vegaLiteToPlot(spec: any): any {
}
const configWithZ = {
- ...baseConfig,
+ ...unstackedConfig,
z: colorField || undefined,
};
return markFunction(sortedData, configWithZ);
} else {
// Regular mark without stacking
- return markFunction(data, baseConfig);
+ return markFunction(data, unstackedConfig);
}
};
diff --git a/packages/graphic-walker/src/vis/spec/stack.test.ts b/packages/graphic-walker/src/vis/spec/stack.test.ts
new file mode 100644
index 00000000..4b085d38
--- /dev/null
+++ b/packages/graphic-walker/src/vis/spec/stack.test.ts
@@ -0,0 +1,22 @@
+import { IStackMode } from '../../interfaces';
+import { channelStack } from './stack';
+
+describe('channelStack', () => {
+ test.each([
+ ['stack', undefined],
+ ['zero', undefined],
+ ['none', null],
+ ['normalize', 'normalize'],
+ ['center', 'center'],
+ ] as Array<[IStackMode, unknown]>)('maps %s to the Vega-Lite stack contract', (mode, expected) => {
+ const encoding: Record<string, any> = {
+ x: { field: 'value', type: 'quantitative' },
+ y: { field: 'category', type: 'nominal' },
+ };
+
+ channelStack(encoding, mode);
+
+ expect(encoding.x.stack).toBe(expected);
+ expect('stack' in encoding.y).toBe(false);
+ });
+});