Skip to content

An open source alternative to Tableau. Embeddable visual analytic

feat(explain): Tableau-style evidence chart semantics (gray context + accent)

Elwynn Chen47ef046982c7
diff --git a/docs/explain-data-worklog.md b/docs/explain-data-worklog.md
index b04ab0d8..451eac0c 100644
--- a/docs/explain-data-worklog.md
+++ b/docs/explain-data-worklog.md
@@ -117,3 +117,4 @@
| 2026-07-08 | 用户 | 反馈 | 借鉴 Tableau master-detail:列表纯文本 + 单图详情,避免一次渲染十几张重图拉垮计算。 |
| 2026-07-08 | Kernel | K-fmt-2 | 三个证据图 spec 由固定 320px 改为 `width: 'container'`(详情面板自适应),height 统一 220。 |
| 2026-07-08 | Executor | E-UI-3 | 重写 Explain Data 为 Tableau-style master-detail 布局:左侧固定 `w-72` 文本列表按解释类型分组并支持 chip 过滤/自动选择,右侧 detail 仅渲染当前选中洞察的描述、单个 `EvidenceChart` 与证据表(全对话框唯一 vega 实例);新增选中 mark subtitle 与三语 `explain.detail.empty`,保留 loading/truncation/skipped footer。验证:jest 283 测试、tsc 通过;`<EvidenceChart` JSX grep 仅 1 处。(Executor 沙箱无法写本文件,由 Kernel 代记) |
+| 2026-07-08 | Kernel | K-viz | 证据图视觉语义改造(用户指定 Kernel 直做):新增 `vizTheme.ts`(灰=语境、固定 accent=选中,主题无关);构成图由并排双色柱改为子弹图式重叠(宽灰底柱 + 窄实色柱,`width:{band}`);散点图灰底点 + 大号实色选中点置顶;直方图灰色常规箱 + 实色极端箱与围栏线。新增 specCompile.test:金标准产出的全部 spec 必须零 warning 通过 vega-lite compile。 |
diff --git a/packages/graphic-walker/src/lib/explain/explainers/extremeValue.ts b/packages/graphic-walker/src/lib/explain/explainers/extremeValue.ts
index 8795a549..e0e11147 100644
--- a/packages/graphic-walker/src/lib/explain/explainers/extremeValue.ts
+++ b/packages/graphic-walker/src/lib/explain/explainers/extremeValue.ts
@@ -1,6 +1,7 @@
import type { IRow, IViewField } from '../../../interfaces';
import { getMeaAggKey } from '../../../utils';
import { formatMeasureValue } from '../format';
+import { ACCENT_COLOR, CONTEXT_COLOR, LEGEND_BOTTOM } from '../vizTheme';
import { detectIqrOutliers, outlierImpact, type ISensitiveAggregator } from '../stats/quantile';
import { EXPLAIN_COUNT_KEY, markPrescreenQuery, markRawQuery } from '../queries';
import type { IExplainContext, IExplainer, IExplanation, IExplanationStrength } from '../types';
@@ -43,32 +44,43 @@ function strengthOf(impact: number): IExplanationStrength {
return 'weak';
}
+const HIST_GROUP_EXTREME = 'Extreme records';
+const HIST_GROUP_NORMAL = 'Records';
+
/** deterministic downsample preserving outliers: every k-th value + all outliers */
-function sampleForHistogram(values: number[], outlierIndices: Set<number>): number[] {
- if (values.length <= MAX_HISTOGRAM_POINTS) return values;
- const step = Math.ceil(values.length / MAX_HISTOGRAM_POINTS);
- const sampled: number[] = [];
+function sampleForHistogram(values: number[], outlierIndices: Set<number>): { value: number; group: string }[] {
+ const step = values.length <= MAX_HISTOGRAM_POINTS ? 1 : Math.ceil(values.length / MAX_HISTOGRAM_POINTS);
+ const sampled: { value: number; group: string }[] = [];
for (let i = 0; i < values.length; i++) {
- if (i % step === 0 || outlierIndices.has(i)) sampled.push(values[i]);
+ const isOutlier = outlierIndices.has(i);
+ if (i % step === 0 || isOutlier) {
+ sampled.push({ value: values[i], group: isOutlier ? HIST_GROUP_EXTREME : HIST_GROUP_NORMAL });
+ }
}
return sampled;
}
-function histogramSpec(values: number[], lowerFence: number, upperFence: number, measureName: string): Record<string, unknown> {
+function histogramSpec(values: { value: number; group: string }[], lowerFence: number, upperFence: number, measureName: string): Record<string, unknown> {
return {
width: 'container',
height: 220,
- data: { values: values.map((v) => ({ value: v })) },
+ data: { values },
layer: [
{
- mark: { type: 'bar', opacity: 0.85 },
+ mark: { type: 'bar' },
encoding: {
x: { field: 'value', bin: { maxbins: 30 }, type: 'quantitative', title: measureName },
y: { aggregate: 'count', type: 'quantitative', title: null },
+ color: {
+ field: 'group',
+ type: 'nominal',
+ scale: { domain: [HIST_GROUP_EXTREME, HIST_GROUP_NORMAL], range: [ACCENT_COLOR, CONTEXT_COLOR] },
+ legend: LEGEND_BOTTOM,
+ },
},
},
- { mark: { type: 'rule', strokeDash: [4, 4] }, encoding: { x: { datum: lowerFence } } },
- { mark: { type: 'rule', strokeDash: [4, 4] }, encoding: { x: { datum: upperFence } } },
+ { mark: { type: 'rule', strokeDash: [4, 4], color: ACCENT_COLOR }, encoding: { x: { datum: lowerFence } } },
+ { mark: { type: 'rule', strokeDash: [4, 4], color: ACCENT_COLOR }, encoding: { x: { datum: upperFence } } },
],
};
}
diff --git a/packages/graphic-walker/src/lib/explain/explainers/modelCommon.ts b/packages/graphic-walker/src/lib/explain/explainers/modelCommon.ts
index acc55a4d..a42b0484 100644
Binary files a/packages/graphic-walker/src/lib/explain/explainers/modelCommon.ts and b/packages/graphic-walker/src/lib/explain/explainers/modelCommon.ts differ
diff --git a/packages/graphic-walker/src/lib/explain/explainers/uniqueMark.ts b/packages/graphic-walker/src/lib/explain/explainers/uniqueMark.ts
index 300c7d5d..13408812 100644
--- a/packages/graphic-walker/src/lib/explain/explainers/uniqueMark.ts
+++ b/packages/graphic-walker/src/lib/explain/explainers/uniqueMark.ts
@@ -1,6 +1,7 @@
import type { IRow, IViewField } from '../../../interfaces';
import { getMeaAggKey } from '../../../utils';
import { categoryLabel } from '../format';
+import { GROUP_COLOR_SCALE, GROUP_CONTEXT, GROUP_SELECTED, LEGEND_BOTTOM } from '../vizTheme';
import { gTestPValue, jsDistance, laplaceSmooth, subtractMass } from '../stats/divergence';
import { ADDITIVE_SAFE_AGGS, EXPLAIN_COUNT_KEY, complementaryDimensions, isMarkRow, markLevelQuery } from '../queries';
import type { IExplainContext, IExplainer, IExplanation, IExplanationStrength } from '../types';
@@ -114,21 +115,36 @@ function compositionSpec(
siblingShares: number[],
candidateName: string
): Record<string, unknown> {
- const values = categories.flatMap((category, i) => [
- { category: String(category), group: 'selected', share: markShares[i] },
- { category: String(category), group: 'siblings', share: siblingShares[i] },
- ]);
+ // bullet-style overlay: wide gray context bars, narrow accent bars on top
+ const values = categories.map((category, i) => ({
+ category: String(category),
+ selected: markShares[i],
+ siblings: siblingShares[i],
+ }));
return {
width: 'container',
height: 220,
data: { values },
- mark: { type: 'bar' },
encoding: {
x: { field: 'category', type: 'nominal', title: candidateName, sort: null },
- xOffset: { field: 'group' },
- y: { field: 'share', type: 'quantitative', title: 'share', axis: { format: '.0%' } },
- color: { field: 'group', type: 'nominal', legend: { orient: 'bottom', title: null } },
+ y: { type: 'quantitative', title: 'share of records', axis: { format: '.0%' } },
},
+ layer: [
+ {
+ mark: { type: 'bar', width: { band: 0.85 } },
+ encoding: {
+ y: { field: 'siblings' },
+ color: { datum: GROUP_CONTEXT, scale: GROUP_COLOR_SCALE, legend: LEGEND_BOTTOM },
+ },
+ },
+ {
+ mark: { type: 'bar', width: { band: 0.45 } },
+ encoding: {
+ y: { field: 'selected' },
+ color: { datum: GROUP_SELECTED, scale: GROUP_COLOR_SCALE },
+ },
+ },
+ ],
};
}
diff --git a/packages/graphic-walker/src/lib/explain/specCompile.test.ts b/packages/graphic-walker/src/lib/explain/specCompile.test.ts
new file mode 100644
index 00000000..11f209c9
--- /dev/null
+++ b/packages/graphic-walker/src/lib/explain/specCompile.test.ts
@@ -0,0 +1,71 @@
+import { compile } from 'vega-lite';
+import type { IRow, IViewField } from '../../interfaces';
+import { getTestComputation } from './testUtils';
+import { explainMarkAll } from './engine';
+import { defaultExplainers } from './index';
+import type { IExplainContext } from './types';
+
+/**
+ * Every evidence chartSpec produced over the golden dataset must compile as
+ * valid vega-lite — schema mistakes (band widths, condition syntax, layered
+ * encodings) otherwise surface only as silent runtime warnings in the UI.
+ */
+
+const field = (fid: string, analyticType: 'dimension' | 'measure', semanticType: 'nominal' | 'quantitative', aggName?: string): IViewField =>
+ ({ fid, name: fid, analyticType, semanticType, aggName } as unknown as IViewField);
+
+function makeDataset(): IRow[] {
+ const rows: IRow[] = [];
+ for (let m = 0; m < 12; m++) {
+ const onlineShare = 0.2 + 0.05 * m;
+ for (let i = 0; i < 30; i++) {
+ const online = i < 30 * onlineShare;
+ const sales = m === 11 && i === 0 ? 10000 : 40 + (online ? 60 : 0) + (i % 5);
+ rows.push({
+ month: `M${String(m + 1).padStart(2, '0')}`,
+ channel: online ? 'online' : 'offline',
+ age: 21 + (i % 40),
+ sales,
+ traffic: 2 * sales + (i % 3),
+ });
+ }
+ }
+ return rows;
+}
+
+it('all evidence chart specs over the golden dataset compile as valid vega-lite', async () => {
+ const ctx: IExplainContext = {
+ allFields: [
+ field('month', 'dimension', 'nominal'),
+ field('channel', 'dimension', 'nominal'),
+ field('age', 'dimension', 'quantitative'),
+ field('sales', 'measure', 'quantitative', 'mean'),
+ field('traffic', 'measure', 'quantitative', 'sum'),
+ ],
+ viewDimensions: [field('month', 'dimension', 'nominal')],
+ viewMeasures: [field('sales', 'measure', 'quantitative', 'mean')],
+ viewFilters: [],
+ selectedMark: { month: 'M12' },
+ };
+ const results = await explainMarkAll(ctx, getTestComputation(makeDataset()), defaultExplainers);
+ const specs = results.flatMap((r) => r.explanations.map((e) => e.evidence.chartSpec)).filter(Boolean);
+ // the planted dataset must exercise all three spec builders
+ // (histogram, scatter, bullet composition)
+ expect(specs.length).toBeGreaterThanOrEqual(3);
+ const warnings: string[] = [];
+ for (const spec of specs) {
+ const compiled = compile(spec as never, {
+ logger: {
+ level: () => 0,
+ warn: (...args: unknown[]) => warnings.push(args.join(' ')),
+ info: () => undefined,
+ debug: () => undefined,
+ error: (...args: unknown[]) => {
+ throw new Error(`vega-lite error: ${args.join(' ')}`);
+ },
+ } as never,
+ });
+ expect(compiled.spec).toBeDefined();
+ }
+ expect(warnings).toEqual([]);
+});
diff --git a/packages/graphic-walker/src/lib/explain/vizTheme.ts b/packages/graphic-walker/src/lib/explain/vizTheme.ts
new file mode 100644
index 00000000..67f32e9e
--- /dev/null
+++ b/packages/graphic-walker/src/lib/explain/vizTheme.ts
@@ -0,0 +1,24 @@
+/**
+ * Visual identity for evidence charts (Tableau-inspired):
+ * neutral gray = context (all marks / in-range records),
+ * one fixed accent = the selected mark / the spotlighted records.
+ *
+ * The accent is intentionally independent of the host chart theme — evidence
+ * charts are analysis UI, not user visualizations, and a stable
+ * gray-vs-accent contrast keeps their semantics readable on any theme.
+ * Both colors are chosen to work on light and dark backgrounds.
+ */
+
+export const CONTEXT_COLOR = '#9aa4b2';
+export const ACCENT_COLOR = '#3b82f6';
+
+export const GROUP_SELECTED = 'Selected mark';
+export const GROUP_CONTEXT = 'All other marks';
+
+/** shared 2-entry color scale so every evidence chart reads the same way */
+export const GROUP_COLOR_SCALE = {
+ domain: [GROUP_SELECTED, GROUP_CONTEXT],
+ range: [ACCENT_COLOR, CONTEXT_COLOR],
+};
+
+export const LEGEND_BOTTOM = { orient: 'bottom', title: null };