-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnormalizeY.ts
79 lines (71 loc) · 2.59 KB
/
normalizeY.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { deepMix } from '@antv/util';
import { mean, deviation, median, sum, max, min } from 'd3-array';
import { isUnset } from '../utils/helper';
import { TransformComponent as TC } from '../runtime';
import { NormalizeYTransform } from '../spec';
import { column, columnOf } from './utils/helper';
import { createGroups } from './utils/order';
export type NormalizeYOptions = Omit<NormalizeYTransform, 'type'>;
function normalizeBasis(basis: NormalizeYOptions['basis']) {
if (typeof basis === 'function') return basis;
const registry = {
min: (I, Y) => min(I, (i) => Y[+i]),
max: (I, Y) => max(I, (i) => Y[+i]),
first: (I, Y) => Y[I[0]],
last: (I, Y) => Y[I[I.length - 1]],
mean: (I, Y) => mean(I, (i) => Y[+i]),
median: (I, Y) => median(I, (i) => Y[+i]),
sum: (I, Y) => sum(I, (i) => Y[+i]),
deviation: (I, Y) => deviation(I, (i) => Y[+i]),
};
return registry[basis] || max;
}
/**
* Group marks into series by specified channels, and then transform
* each series's value, say to transform them relative to some basis
* to apply a moving average.
*/
export const NormalizeY: TC<NormalizeYOptions> = (options = {}) => {
const { groupBy = 'x', basis = 'max' } = options;
return (I, mark) => {
const { encode, tooltip } = mark;
const { x, ...rest } = encode;
// Extract and create new channels starts with y, such as y, y1.
const Yn = Object.entries(rest)
.filter(([k]) => k.startsWith('y'))
.map(([k]) => [k, columnOf(encode, k)[0]] as const);
const [, Y] = Yn.find(([k]) => k === 'y');
const newYn = Yn.map(([k]) => [k, new Array(I.length)] as const);
// Group marks into series by specified keys.
const groups = createGroups(groupBy, I, mark);
// Transform y channels for each group based on basis.
const basisFunction = normalizeBasis(basis);
for (const I of groups) {
// Compute basis only base on y.
const basisValue = basisFunction(I, Y);
for (const i of I) {
for (let j = 0; j < Yn.length; j++) {
const [, V] = Yn[j];
const [, newV] = newYn[j];
newV[i] = +V[i] / basisValue;
}
}
}
const specifiedTooltip =
isUnset(tooltip) || (tooltip?.items && tooltip?.items.length !== 0);
return [
I,
deepMix({}, mark, {
encode: Object.fromEntries(
newYn.map(([k, v]) => [k, column(v, columnOf(encode, k)[1])]),
),
// Infer tooltip item.
...(!specifiedTooltip &&
encode.y0 && {
tooltip: { items: [{ channel: 'y0' }] },
}),
}),
];
};
};
NormalizeY.props = {};