Skip to content

Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.

[Feat] Add custom color scale for aggregate layers (#2860)

Igor Dykhtaa897715cc9ea
diff --git a/src/components/src/common/column-stats-chart.tsx b/src/components/src/common/column-stats-chart.tsx
index a80463fe5..a16c4f4c0 100644
--- a/src/components/src/common/column-stats-chart.tsx
+++ b/src/components/src/common/column-stats-chart.tsx
@@ -7,12 +7,10 @@ import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import styled from 'styled-components';
import {KeplerTable} from '@kepler.gl/table';
-import {Field} from '@kepler.gl/types';
+import {Bin, Field} from '@kepler.gl/types';
import {
ColorBreak,
ColorBreakOrdinal,
- histogramFromThreshold,
- histogramFromValues,
isNumber,
isNumericColorBreaks,
useDimensions
@@ -29,7 +27,6 @@ const COLOR_CHART_TICK_WRAPPER_HEIGHT = 10;
const COLOR_CHART_TICK_HEIGHT = 8;
const COLOR_CHART_TICK_WIDTH = 4;
const COLOR_CHART_TICK_BORDER_COLOR = '#999999';
-const HISTOGRAM_BINS = 30;
const StyledContainer = styled.div.attrs({
className: 'color-chart-loading'
@@ -208,12 +205,18 @@ export type ColumnStatsChartWLoadingProps = {
colorField: Field;
dataset: KeplerTable;
colorBreaks: ColorBreak[] | ColorBreakOrdinal[] | null;
+ allBins: Bin[];
+ filteredBins: Bin[];
+ isFiltered: boolean;
+ histogramDomain: number[];
onChangedUpdater: (ticks: ColorBreak[]) => void;
};
export type ColumnStatsChartProps = {
- field: Field;
- dataset: KeplerTable;
+ allBins: Bin[];
+ filteredBins: Bin[];
+ isFiltered: boolean;
+ histogramDomain: number[];
colorBreaks: ColorBreak[];
onChangedUpdater: (ticks: ColorBreak[]) => void;
};
@@ -221,8 +224,10 @@ function ColumnStatsChartFactory(
HistogramPlot: ReturnType<typeof HistogramPlotFactory>
): React.FC<ColumnStatsChartWLoadingProps> {
const ColumnStatsChart: React.FC<ColumnStatsChartProps> = ({
- field,
- dataset,
+ allBins,
+ filteredBins,
+ isFiltered,
+ histogramDomain,
colorBreaks,
onChangedUpdater
}) => {
@@ -241,38 +246,6 @@ function ColumnStatsChartFactory(
isTickChangingRef.current = false;
}, [ticks]);
- const valueAccessor = useMemo(() => {
- return idx => dataset.getValue(field.name, idx);
- }, [dataset, field.name]);
-
- const columnStats = field.filterProps?.columnStats;
-
- // get bins with allIndexes
- const allBins = useMemo(() => {
- if (columnStats?.bins) {
- return columnStats?.bins;
- }
- return histogramFromValues(dataset.allIndexes, HISTOGRAM_BINS, valueAccessor);
- }, [columnStats, dataset.allIndexes, valueAccessor]);
-
- const isFiltered = dataset.filteredIndexForDomain.length !== dataset.allIndexes.length;
-
- // get filteredBins
- const filteredBins = useMemo(() => {
- if (!isFiltered) {
- return allBins;
- }
- // get threholds
- const filterEmptyBins = false;
- const threholds = allBins.map(b => b.x0);
- return histogramFromThreshold(
- threholds,
- dataset.filteredIndexForDomain,
- valueAccessor,
- filterEmptyBins
- );
- }, [dataset, valueAccessor, allBins, isFiltered]);
-
// histograms used by histogram-plot.js
const histogramsByGroup = useMemo(
() => ({
@@ -282,34 +255,6 @@ function ColumnStatsChartFactory(
[allBins, filteredBins]
);
- // get domain (min, max) of histogram
- const histogramDomain = useMemo(() => {
- if (columnStats && columnStats.quantiles && columnStats.mean) {
- // no need to recalcuate min/max/mean if its already in columnStats
- return [
- columnStats.quantiles[0].value,
- columnStats.quantiles[columnStats.quantiles.length - 1].value,
- columnStats.mean
- ];
- }
- let domainMin = Number.POSITIVE_INFINITY;
- let domainMax = Number.NEGATIVE_INFINITY;
- let nValid = 0;
- let domainSum = 0;
- dataset.allIndexes.forEach((x, i) => {
- const val = valueAccessor(x);
- if (isNumber(val)) {
- if (val < domainMin) domainMin = val;
- if (val > domainMax) domainMax = val;
- domainSum += val;
- nValid += 1;
- }
- });
- const histogramMean = nValid > 0 ? domainSum / nValid : 0;
-
- return [domainMin, domainMax, histogramMean];
- }, [dataset, valueAccessor, columnStats]);
-
// get colors from colorBreaks
const domainColors = useMemo(
() => (colorBreaks ? colorBreaks.map(c => c.data) : []),
@@ -417,19 +362,24 @@ function ColumnStatsChartFactory(
colorField,
dataset,
colorBreaks,
+ allBins,
+ filteredBins,
+ isFiltered,
+ histogramDomain,
onChangedUpdater
}) => {
- const fieldName = colorField.name;
- const field = useMemo(() => dataset.getColumnField(fieldName), [dataset, fieldName]);
-
- const isLoading = field?.isLoadingStats;
+ const fieldName = colorField?.name;
+ const field = useMemo(() => (fieldName ? dataset.getColumnField(fieldName) : null), [
+ dataset,
+ fieldName
+ ]);
- if (!isNumericColorBreaks(colorBreaks) || !field) {
+ if (!isNumericColorBreaks(colorBreaks)) {
// TODO: implement display for ordinal breaks
return null;
}
- if (isLoading) {
+ if (field?.isLoadingStats) {
return (
<StyledContainer>
<LoadingSpinner />
@@ -440,8 +390,10 @@ function ColumnStatsChartFactory(
return (
<ColumnStatsChart
colorBreaks={colorBreaks}
- field={field}
- dataset={dataset}
+ allBins={allBins}
+ filteredBins={filteredBins}
+ isFiltered={isFiltered}
+ histogramDomain={histogramDomain}
onChangedUpdater={onChangedUpdater}
/>
);
diff --git a/src/components/src/map-container.tsx b/src/components/src/map-container.tsx
index 3288aab3f..ef76d63ab 100644
--- a/src/components/src/map-container.tsx
+++ b/src/components/src/map-container.tsx
@@ -30,7 +30,8 @@ import {
updateMapboxLayers,
LayerBaseConfig,
VisualChannelDomain,
- EditorLayerUtils
+ EditorLayerUtils,
+ AggregatedBin
} from '@kepler.gl/layers';
import {MapState, MapControls, Viewport, SplitMap, SplitMapLayers} from '@kepler.gl/types';
import {
@@ -465,9 +466,13 @@ export default function MapContainerFactory(
this.props.visStateActions.onLayerHover(info, this.props.index);
};
- _onLayerSetDomain = (idx: number, colorDomain: {domain: VisualChannelDomain}) => {
+ _onLayerSetDomain = (
+ idx: number,
+ value: {domain: VisualChannelDomain; aggregatedBins: AggregatedBin[]}
+ ) => {
this.props.visStateActions.layerConfigChange(this.props.visState.layers[idx], {
- colorDomain: colorDomain.domain
+ colorDomain: value.domain,
+ aggregatedBins: value.aggregatedBins
} as Partial<LayerBaseConfig>);
};
diff --git a/src/components/src/side-panel/layer-panel/aggr-scale-selector.tsx b/src/components/src/side-panel/layer-panel/aggr-scale-selector.tsx
index 8cf0d734c..19dd861f0 100644
--- a/src/components/src/side-panel/layer-panel/aggr-scale-selector.tsx
+++ b/src/components/src/side-panel/layer-panel/aggr-scale-selector.tsx
@@ -6,12 +6,13 @@ import DimensionScaleSelectorFactory from './dimension-scale-selector';
AggrScaleSelectorFactory.deps = [DimensionScaleSelectorFactory];
export function AggrScaleSelectorFactory(DimensionScaleSelector) {
- const AggrScaleSelector = ({channel, layer, onChange, setColorUI, label}) => {
+ const AggrScaleSelector = ({channel, dataset, layer, onChange, setColorUI, label}) => {
const {key} = channel;
const scaleOptions = layer.getScaleOptions(key);
return Array.isArray(scaleOptions) && scaleOptions.length > 1 ? (
<DimensionScaleSelector
+ dataset={dataset}
layer={layer}
channel={channel}
label={label || `${key} Scale`}
diff --git a/src/components/src/side-panel/layer-panel/color-breaks-panel.tsx b/src/components/src/side-panel/layer-panel/color-breaks-panel.tsx
index 3a5dfce57..d16a428e2 100644
--- a/src/components/src/side-panel/layer-panel/color-breaks-panel.tsx
+++ b/src/components/src/side-panel/layer-panel/color-breaks-panel.tsx
@@ -3,7 +3,7 @@
import {SCALE_TYPES} from '@kepler.gl/constants';
import {KeplerTable} from '@kepler.gl/table';
-import {ColorUI, Field} from '@kepler.gl/types';
+import {Bin, ColorUI, Field} from '@kepler.gl/types';
import {
ColorBreak,
ColorBreakOrdinal,
@@ -83,6 +83,10 @@ export type ColorBreaksPanelProps = {
dataset: KeplerTable | undefined;
colorField: Field;
isCustomBreaks: boolean;
+ allBins: Bin[];
+ filteredBins: Bin[];
+ isFiltered: boolean;
+ histogramDomain: number[];
setColorUI: SetColorUIFunc;
onScaleChange: (v: string, visConfg?: Record<string, any>) => void;
onApply: (e: React.MouseEvent) => void;
@@ -101,6 +105,10 @@ function ColorBreaksPanelFactory(
dataset,
colorField,
isCustomBreaks,
+ allBins,
+ filteredBins,
+ isFiltered,
+ histogramDomain,
setColorUI,
onScaleChange,
onApply,
@@ -168,6 +176,10 @@ function ColorBreaksPanelFactory(
colorField={colorField}
dataset={dataset}
colorBreaks={currentBreaks}
+ allBins={allBins}
+ filteredBins={filteredBins}
+ isFiltered={isFiltered}
+ histogramDomain={histogramDomain}
onChangedUpdater={onColumnStatsChartChanged}
/>
) : null}
diff --git a/src/components/src/side-panel/layer-panel/color-scale-selector.tsx b/src/components/src/side-panel/layer-panel/color-scale-selector.tsx
index 5bf5cc38d..7abf31d6c 100644
--- a/src/components/src/side-panel/layer-panel/color-scale-selector.tsx
+++ b/src/components/src/side-panel/layer-panel/color-scale-selector.tsx
@@ -4,14 +4,17 @@
import React, {useCallback, useMemo, useState} from 'react';
import styled from 'styled-components';
-import {SCALE_TYPES} from '@kepler.gl/constants';
-import {Layer, VisualChannelDomain} from '@kepler.gl/layers';
+import {ALL_FIELD_TYPES, SCALE_TYPES} from '@kepler.gl/constants';
+import {AggregatedBin, Layer, VisualChannelDomain} from '@kepler.gl/layers';
import {KeplerTable} from '@kepler.gl/table';
import {ColorRange, ColorUI, Field, NestedPartial} from '@kepler.gl/types';
import {
colorBreaksToColorMap,
getLayerColorScale,
getLegendOfScale,
+ histogramFromValues,
+ histogramFromThreshold,
+ getHistogramDomain,
hasColorMap
} from '@kepler.gl/utils';
@@ -25,6 +28,8 @@ import Typeahead from '../../common/item-selector/typeahead';
type TippyInstance = any; // 'tippy-js'
+const HISTOGRAM_BINS = 30;
+
export type ScaleOption = {
label: string;
value: string;
@@ -50,6 +55,7 @@ export type ColorScaleSelectorProps = {
searchable: boolean;
displayOption: string;
getOptionValue: string;
+ aggregatedBins?: AggregatedBin[];
};
const DropdownPropContext = React.createContext({});
@@ -126,6 +132,7 @@ function ColorScaleSelectorFactory(
onSelect,
scaleType,
domain,
+ aggregatedBins,
range,
setColorUI,
colorUIConfig,
@@ -151,10 +158,62 @@ function ColorScaleSelectorFactory(
const colorBreaks = useMemo(
() =>
- colorScale ? getLegendOfScale({scale: colorScale, scaleType, fieldType: field.type}) : null,
- [colorScale, scaleType, field.type]
+ colorScale
+ ? getLegendOfScale({
+ scale: colorScale,
+ scaleType,
+ fieldType: field?.type ?? ALL_FIELD_TYPES.real
+ })
+ : null,
+ [colorScale, scaleType, field?.type]
);
+ const columnStats = field?.filterProps?.columnStats;
+
+ const fieldValueAccessor = useMemo(() => {
+ return field
+ ? idx => dataset.getValue(field.name, idx)
+ : idx => dataset.dataContainer.rowAsArray(idx);
+ }, [dataset, field]);
+
+ // aggregatedBins should be the raw data
+ const allBins = useMemo(() => {
+ if (aggregatedBins) {
+ return histogramFromValues(
+ Object.values(aggregatedBins).map(bin => bin.i),
+ HISTOGRAM_BINS,
+ idx => aggregatedBins[idx].value
+ );
+ }
+ return columnStats?.bins
+ ? columnStats?.bins
+ : histogramFromValues(dataset.allIndexes, HISTOGRAM_BINS, fieldValueAccessor);
+ }, [aggregatedBins, columnStats, dataset, fieldValueAccessor]);
+
+ const histogramDomain = useMemo(() => {
+ return getHistogramDomain({aggregatedBins, columnStats, dataset, fieldValueAccessor});
+ }, [dataset, fieldValueAccessor, aggregatedBins, columnStats]);
+
+ const isFiltered = aggregatedBins
+ ? false
+ : dataset.filteredIndexForDomain.length !== dataset.allIndexes.length;
+
+ // get filteredBins (not apply to aggregate layer)
+ const filteredBins = useMemo(() => {
+ if (!isFiltered) {
+ return allBins;
+ }
+ // get threholds
+ const filterEmptyBins = false;
+ const threholds = allBins.map(b => b.x0);
+ return histogramFromThreshold(
+ threholds,
+ dataset.filteredIndexForDomain,
+ fieldValueAccessor,
+ filterEmptyBins
+ );
+ }, [dataset, fieldValueAccessor, allBins, isFiltered]);
+
const onSelectScale = useCallback(
val => {
// highlight selected option
@@ -221,6 +280,10 @@ function ColorScaleSelectorFactory(
colorUIConfig,
colorBreaks,
isCustomBreaks,
+ allBins,
+ filteredBins,
+ isFiltered,
+ histogramDomain,
onScaleChange: onSelect,
onApply,
onCancel
diff --git a/src/components/src/side-panel/layer-panel/dimension-scale-selector.tsx b/src/components/src/side-panel/layer-panel/dimension-scale-selector.tsx
index b3661add5..896865691 100644
--- a/src/components/src/side-panel/layer-panel/dimension-scale-selector.tsx
+++ b/src/components/src/side-panel/layer-panel/dimension-scale-selector.tsx
@@ -51,7 +51,9 @@ function DimensionScaleSelectorFactory(
value: op
}));
const disabled = scaleOptions.length < 2;
- const isColorScale = channelScaleType === CHANNEL_SCALES.color;
+ const isColorScale =
+ channelScaleType === CHANNEL_SCALES.color ||
+ (layer.config.aggregatedBins && channelScaleType === CHANNEL_SCALES.colorAggr);
const onSelect = useCallback(
(val, newRange) => onChange({[scale]: val}, key, newRange ? {[range]: newRange} : undefined),
@@ -87,6 +89,7 @@ function DimensionScaleSelectorFactory(
onSelect={onSelect}
scaleType={scaleType}
domain={layer.config[domain]}
+ aggregatedBins={layer.config.aggregatedBins}
range={layer.config.visConfig[range]}
setColorUI={_setColorUI}
colorUIConfig={layer.config.colorUI?.[range]}
diff --git a/src/components/src/side-panel/layer-panel/layer-configurator.tsx b/src/components/src/side-panel/layer-panel/layer-configurator.tsx
index ebec6b7a9..eb6b97291 100644
--- a/src/components/src/side-panel/layer-panel/layer-configurator.tsx
+++ b/src/components/src/side-panel/layer-panel/layer-configurator.tsx
@@ -294,12 +294,12 @@ export default function LayerConfiguratorFactory(
{/* Color */}
<LayerConfigGroup label={'layer.color'} collapsible>
<LayerColorRangeSelector {...visConfiguratorProps} />
+ <AggrScaleSelector {...layerChannelConfigProps} channel={layer.visualChannels.color} />
<ChannelByValueSelector
channel={layer.visualChannels.color}
{...layerChannelConfigProps}
/>
<ConfigGroupCollapsibleContent>
- <AggrScaleSelector {...layerConfiguratorProps} channel={layer.visualChannels.color} />
{layer.visConfigSettings.colorAggregation.condition(layer.config) ? (
<AggregationTypeSelector
{...layer.visConfigSettings.colorAggregation}
@@ -380,12 +380,10 @@ export default function LayerConfiguratorFactory(
channel={layer.visualChannels.color}
{...layerChannelConfigProps}
/>
-
+ <AggrScaleSelector {...layerChannelConfigProps} channel={layer.visualChannels.color} />
<LayerColorRangeSelector {...visConfiguratorProps} />
<ConfigGroupCollapsibleContent>
- <AggrScaleSelector {...layerConfiguratorProps} channel={layer.visualChannels.color} />
-
{layer.visConfigSettings.colorAggregation.condition(layer.config) ? (
<AggregationTypeSelector
{...layer.visConfigSettings.colorAggregation}
@@ -440,7 +438,7 @@ export default function LayerConfiguratorFactory(
/>
) : null}
<AggrScaleSelector
- {...layerConfiguratorProps}
+ {...layerChannelConfigProps}
channel={layer.visualChannels.size}
label={'Height Scale'}
/>
diff --git a/src/constants/src/default-settings.ts b/src/constants/src/default-settings.ts
index 96fa61b2e..c445296e1 100644
--- a/src/constants/src/default-settings.ts
+++ b/src/constants/src/default-settings.ts
@@ -633,16 +633,26 @@ export const linearFieldScaleFunctions = {
[CHANNEL_SCALES.size]: [SCALE_TYPES.linear, SCALE_TYPES.sqrt, SCALE_TYPES.log]
};
+const DEFAULT_AGGREGATION_COLOR_SCALES = [
+ SCALE_TYPES.quantize,
+ SCALE_TYPES.quantile,
+ SCALE_TYPES.custom
+];
+
export const linearFieldAggrScaleFunctions = {
- [CHANNEL_SCALES.colorAggr]: {
- [AGGREGATION_TYPES.average]: [SCALE_TYPES.quantize, SCALE_TYPES.quantile],
- [AGGREGATION_TYPES.maximum]: [SCALE_TYPES.quantize, SCALE_TYPES.quantile],
- [AGGREGATION_TYPES.minimum]: [SCALE_TYPES.quantize, SCALE_TYPES.quantile],
- [AGGREGATION_TYPES.median]: [SCALE_TYPES.quantize, SCALE_TYPES.quantile],
- [AGGREGATION_TYPES.stdev]: [SCALE_TYPES.quantize, SCALE_TYPES.quantile],
- [AGGREGATION_TYPES.sum]: [SCALE_TYPES.quantize, SCALE_TYPES.quantile],
- [AGGREGATION_TYPES.variance]: [SCALE_TYPES.quantize, SCALE_TYPES.quantile]
- },
+ [CHANNEL_SCALES.colorAggr]: [
+ AGGREGATION_TYPES.count,
+ AGGREGATION_TYPES.average,
+ AGGREGATION_TYPES.maximum,
+ AGGREGATION_TYPES.minimum,
+ AGGREGATION_TYPES.median,
+ AGGREGATION_TYPES.stdev,
+ AGGREGATION_TYPES.sum,
+ AGGREGATION_TYPES.variance
+ ].reduce((prev, cur) => {
+ prev[cur] = DEFAULT_AGGREGATION_COLOR_SCALES;
+ return prev;
+ }, {}),
[CHANNEL_SCALES.sizeAggr]: {
[AGGREGATION_TYPES.average]: [SCALE_TYPES.linear, SCALE_TYPES.sqrt, SCALE_TYPES.log],
@@ -688,7 +698,7 @@ export const notSupportAggrOpts = {
*/
export const DEFAULT_AGGREGATION = {
[CHANNEL_SCALES.colorAggr]: {
- [AGGREGATION_TYPES.count]: [SCALE_TYPES.quantize, SCALE_TYPES.quantile]
+ [AGGREGATION_TYPES.count]: DEFAULT_AGGREGATION_COLOR_SCALES
},
[CHANNEL_SCALES.sizeAggr]: {
[AGGREGATION_TYPES.count]: [SCALE_TYPES.linear, SCALE_TYPES.sqrt, SCALE_TYPES.log]
diff --git a/src/deckgl-layers/src/layer-utils/cpu-aggregator.ts b/src/deckgl-layers/src/layer-utils/cpu-aggregator.ts
index f7e70f8f3..3c7d539d2 100644
--- a/src/deckgl-layers/src/layer-utils/cpu-aggregator.ts
+++ b/src/deckgl-layers/src/layer-utils/cpu-aggregator.ts
@@ -126,12 +126,21 @@ export function getDimensionValueDomain(this: CPUAggregator, step, props, dimens
return;
}
- // for log and sqrt scale, returns linear domain by default
- // TODO: support other scale function domain in bin sorter
- const valueDomain = this.state.dimensions[key].sortedBins.getValueDomainByScale(
- props[scaleType.prop],
- [props[lowerPercentile.prop], props[upperPercentile.prop]]
- );
+ let valueDomain =
+ // for log and sqrt scale, returns linear domain by default
+ // TODO: support other scale function domain in bin sorter
+ this.state.dimensions[key].sortedBins.getValueDomainByScale(props[scaleType.prop], [
+ props[lowerPercentile.prop],
+ props[upperPercentile.prop]
+ ]);
+
+ if (props.colorScaleType === 'custom' && props.colorMap) {
+ // for custom scale, return custom breaks as value domain directly
+ valueDomain = props.colorMap.reduce(
+ (prev, cur) => (Number.isFinite(cur[0]) ? prev.concat(cur[0]) : prev),
+ []
+ );
+ }
this._setDimensionState(key, {valueDomain});
}
@@ -156,7 +165,8 @@ export function getDimensionScale(this: CPUAggregator, step, props, dimensionUpd
.range(dimensionFixed ? dimensionDomain : dimensionRange);
if (typeof onSet === 'object' && typeof props[onSet.props] === 'function') {
- props[onSet.props](scaleFunc.domain());
+ const sortedBins = this.state.dimensions[key].sortedBins;
+ props[onSet.props]({domain: scaleFunc.domain(), aggregatedBins: sortedBins.binMap});
}
this._setDimensionState(key, {scaleFunc});
}
@@ -227,7 +237,10 @@ function getSubLayerAccessor(dimensionState, dimension) {
const cv = bin && bin.value;
const domain = scaleFunc.domain();
- const isValueInDomain = cv >= domain[0] && cv <= domain[domain.length - 1];
+ const isValueInDomain =
+ scaleFunc.scaleType === 'custom'
+ ? cv >= sortedBins.minValue && cv <= sortedBins.maxValue
+ : cv >= domain[0] && cv <= domain[domain.length - 1];
// if cell value is outside domain, set alpha to 0
return isValueInDomain ? scaleFunc(cv) : dimension.nullValue;
diff --git a/src/layers/src/aggregation-layer.ts b/src/layers/src/aggregation-layer.ts
index 3514732db..95501f0bc 100644
--- a/src/layers/src/aggregation-layer.ts
+++ b/src/layers/src/aggregation-layer.ts
@@ -379,6 +379,7 @@ export default class AggregationLayer extends Layer {
// color
colorRange: this.getColorRange(visConfig.colorRange),
+ colorMap: visConfig.colorRange.colorMap,
colorScaleType: this.config.colorScale,
upperPercentile: visConfig.percentile[1],
lowerPercentile: visConfig.percentile[0],
diff --git a/src/layers/src/base-layer.ts b/src/layers/src/base-layer.ts
index d0d36d100..e396ae9c8 100644
--- a/src/layers/src/base-layer.ts
+++ b/src/layers/src/base-layer.ts
@@ -82,6 +82,12 @@ export type VisualChannelDomain = number[] | string[];
export type VisualChannelField = Field | null;
export type VisualChannelScale = keyof typeof SCALE_TYPES;
+export type AggregatedBin = {
+ i: number;
+ value: number;
+ counts: number;
+};
+
export type LayerBaseConfig = {
dataId: string;
label: string;
@@ -104,6 +110,10 @@ export type LayerBaseConfig = {
enabled: boolean;
domain?: [number, number] | null;
};
+
+ // for aggregate layer, aggregatedBins is returned for custom color scale
+ aggregatedBins?: AggregatedBin[];
+
columnMode?: string;
heightField?: VisualChannelField;
heightDomain?: VisualChannelDomain;
diff --git a/src/layers/src/cluster-layer/cluster-layer.ts b/src/layers/src/cluster-layer/cluster-layer.ts
index 13f221fab..acca7038e 100644
--- a/src/layers/src/cluster-layer/cluster-layer.ts
+++ b/src/layers/src/cluster-layer/cluster-layer.ts
@@ -118,6 +118,7 @@ export default class ClusterLayer extends AggregationLayer {
// color
colorRange: this.getColorRange(visConfig.colorRange),
+ colorMap: visConfig.colorRange.colorMap,
colorScaleType: this.config.colorScale,
colorAggregation: visConfig.colorAggregation,
diff --git a/src/utils/src/data-scale-utils.ts b/src/utils/src/data-scale-utils.ts
index c06bb621d..832e64c43 100644
--- a/src/utils/src/data-scale-utils.ts
+++ b/src/utils/src/data-scale-utils.ts
@@ -6,7 +6,8 @@ import moment from 'moment';
import {notNullorUndefined} from '@kepler.gl/common-utils';
import {ALL_FIELD_TYPES, SCALE_FUNC, SCALE_TYPES} from '@kepler.gl/constants';
-// import {Layer, VisualChannel, VisualChannelDomain} from '@kepler.gl/layers';
+// import {AggregatedBin, Layer, VisualChannel, VisualChannelDomain} from '@kepler.gl/layers';
+// import {FilterProps, KeplerTable} from '@kepler.gl/layers';
import {ColorMap, ColorRange, HexColor, MapState} from '@kepler.gl/types';
import {isRgbColor, rgbToHex} from './color-utils';
@@ -32,6 +33,9 @@ export type D3ScaleFunction = Record<string, any> & ((x: any) => any);
type Layer = any;
type VisualChannel = any;
type VisualChannelDomain = any;
+type AggregatedBin = any;
+type FilterProps = any;
+type KeplerTable = any;
export type LabelFormat = (n: number) => string;
type dataValueAccessor = <T>(param: T) => T;
@@ -421,3 +425,55 @@ export function colorMapToColorBreaks(colorMap?: ColorMap): ColorBreak[] | null
export function isNumericColorBreaks(colorBreaks: unknown): colorBreaks is ColorBreak[] {
return Array.isArray(colorBreaks) && colorBreaks.length && colorBreaks[0].inputs;
}
+
+// return domainMin, domainMax, histogramMean
+export function getHistogramDomain({
+ aggregatedBins,
+ columnStats,
+ dataset,
+ fieldValueAccessor
+}: {
+ aggregatedBins?: AggregatedBin[];
+ columnStats?: FilterProps['columnStats'];
+ dataset?: KeplerTable;
+ fieldValueAccessor: (idx: unknown) => number;
+}) {
+ let domainMin = Number.POSITIVE_INFINITY;
+ let domainMax = Number.NEGATIVE_INFINITY;
+ let nValid = 0;
+ let domainSum = 0;
+
+ if (aggregatedBins) {
+ Object.values(aggregatedBins).forEach(bin => {
+ const val = bin.value;
+ if (isNumber(val)) {
+ if (val < domainMin) domainMin = val;
+ if (val > domainMax) domainMax = val;
+ domainSum += val;
+ nValid += 1;
+ }
+ });
+ } else {
+ if (columnStats && columnStats.quantiles && columnStats.mean) {
+ // no need to recalcuate min/max/mean if its already in columnStats
+ return [
+ columnStats.quantiles[0].value,
+ columnStats.quantiles[columnStats.quantiles.length - 1].value,
+ columnStats.mean
+ ];
+ }
+ if (dataset && fieldValueAccessor) {
+ dataset.allIndexes.forEach((x, i) => {
+ const val = fieldValueAccessor(x);
+ if (isNumber(val)) {
+ if (val < domainMin) domainMin = val;
+ if (val > domainMax) domainMax = val;
+ domainSum += val;
+ nValid += 1;
+ }
+ });
+ }
+ }
+ const histogramMean = nValid > 0 ? domainSum / nValid : 0;
+ return [nValid > 0 ? domainMin : 0, nValid > 0 ? domainMax : 0, histogramMean];
+}
diff --git a/src/utils/src/index.ts b/src/utils/src/index.ts
index e730e1ed8..4d9d0ae30 100644
--- a/src/utils/src/index.ts
+++ b/src/utils/src/index.ts
@@ -24,7 +24,7 @@ export {
paletteIsColorBlindSafe,
updateColorRangeByMatchingPalette,
updateCustomColorRangeByColorUI,
- initializeCustomPalette
+ initializeCustomPalette,
} from './color-utils';
export {errorNotification} from './notifications-utils';
@@ -150,7 +150,8 @@ export {
isDomainQuantile,
getDomainStepsbyZoom,
getThresholdsFromQuantiles,
- getQuantLabelFormat
+ getQuantLabelFormat,
+ getHistogramDomain
} from './data-scale-utils';
export type {ColorBreak, ColorBreakOrdinal, DomainQuantiles, DomainStops} from './data-scale-utils';
diff --git a/src/utils/src/plot.ts b/src/utils/src/plot.ts
index 4d887d704..51aaa8ca6 100644
--- a/src/utils/src/plot.ts
+++ b/src/utils/src/plot.ts
@@ -87,7 +87,7 @@ export function histogramFromThreshold(
export function histogramFromValues(
values: (Millisecond | null | number)[],
numBins: number,
- valueAccessor?: (d: unknown) => number
+ valueAccessor?: (d: number) => number
) {
const getBins = d3Histogram().thresholds(numBins);
diff --git a/test/browser/components/common/column-stats-chart-test.js b/test/browser/components/common/column-stats-chart-test.js
index 5902e2e04..14f98fd5d 100644
--- a/test/browser/components/common/column-stats-chart-test.js
+++ b/test/browser/components/common/column-stats-chart-test.js
@@ -22,6 +22,7 @@ import sinon from 'sinon';
import test from 'tape';
import {IntlWrapper, mountWithTheme} from 'test/helpers/component-utils';
import {StateWFilesFiltersLayerColor} from 'test/helpers/mock-state';
+import {histogramFromThreshold, histogramFromValues, getHistogramDomain} from '@kepler.gl/utils';
const ColorBreaksPanel = appInjector.get(ColorBreaksPanelFactory);
const ColumnStatsChart = appInjector.get(ColumnStatsChartFactory);
@@ -57,11 +58,26 @@ const ColumnStatsChartProps = (filterData = false) => {
};
const colorScale = getLayerColorScale({range, domain, scaleType, layer: pointLayer1});
const colorBreaks = getLegendOfScale({scale: colorScale, scaleType, fieldType: colorField.type});
-
+ const fieldValueAccessor = idx => dataset.getValue(colorField.name, idx);
+ const histogramDomain = getHistogramDomain({dataset, fieldValueAccessor});
+ const allBins = histogramFromValues(dataset.allIndexes, 30, fieldValueAccessor);
+ const filteredBins = !filterData
+ ? allBins
+ : histogramFromThreshold(
+ allBins.map(b => b.x0),
+ dataset.filteredIndexForDomain,
+ fieldValueAccessor,
+ false
+ );
+ const isFiltered = filterData;
return {
colorField,
dataset,
colorBreaks,
+ allBins,
+ filteredBins,
+ isFiltered,
+ histogramDomain,
onChangedUpdater: sinon.spy()
};
};
@@ -151,7 +167,7 @@ test('Components -> ColumnStatsChart -> ColorChartHeader', t => {
<ColorChartHeader {...InitialProps} />
</IntlWrapper>
);
- }, 'should not fail rendering ColumnStatsChart');
+ }, 'should not fail rendering ColorChartHeader');
const colorChartHeader = wrapper.find('.color-chart-header');
t.equal(colorChartHeader.length, 1, 'should render 1 ColorChartHeader');
@@ -205,7 +221,6 @@ test('Components -> ColumnStatsChart -> IsLoading', t => {
);
}, 'should not fail rendering ColumnStatsChart');
- t.equal(wrapper.find('.color-chart-loading').length, 1, 'should render loading component');
t.equal(wrapper.find('.color-chart-header').length, 0, 'should not render ColorChartHeader');
t.end();
});
@@ -359,7 +374,7 @@ test('Components -> ColorBreaksPanel -> ColumnStatsChart', t => {
<ColorBreaksPanel {...InitialProps} />
</IntlWrapper>
);
- }, 'should not fail rendering ColumnStatsChart');
+ }, 'should not fail rendering ColorBreaksPanel');
const colorChartTickWrapper = wrapper.find('.color-chart-tick-container');
diff --git a/test/browser/layer-tests/cluster-layer-specs.js b/test/browser/layer-tests/cluster-layer-specs.js
index 96ef3fd72..96483e5bf 100644
--- a/test/browser/layer-tests/cluster-layer-specs.js
+++ b/test/browser/layer-tests/cluster-layer-specs.js
@@ -305,9 +305,18 @@ test('#ClusterLayer -> renderLayer', t => {
expectedScatterplotData,
'should pass correct data to cluster layer'
);
+
+ const expectedColorDomain = {
+ domain: [1, 1, 1],
+ aggregatedBins: {
+ 0: {i: 0, value: 1, counts: 1},
+ 1: {i: 1, value: 1, counts: 1},
+ 2: {i: 2, value: 1, counts: 1}
+ }
+ };
t.deepEqual(
spyLayerCallbacks.args[0][0],
- [1, 1, 1],
+ expectedColorDomain,
'should call onSetLayerDomain with correct domain'
);
diff --git a/test/browser/layer-tests/grid-layer-specs.js b/test/browser/layer-tests/grid-layer-specs.js
index de61036b2..0610a89fa 100644
--- a/test/browser/layer-tests/grid-layer-specs.js
+++ b/test/browser/layer-tests/grid-layer-specs.js
@@ -328,9 +328,14 @@ test('#GridLayer -> renderLayer', t => {
`should pass correct data:${i} to grid cell layer`
);
});
+
+ const expectedLayerDomain = {
+ domain: [1, 2],
+ aggregatedBins: {1: {i: 1, value: 2, counts: 2}, 2: {i: 2, value: 1, counts: 1}}
+ };
t.deepEqual(
spyLayerCallbacks.args[0][0],
- [1, 2],
+ expectedLayerDomain,
'should call onSetLayerDomain with correct domain'
);
@@ -443,10 +448,13 @@ test('#GridLayer -> renderLayer', t => {
{i: 2, value: 1, counts: 1},
{i: 1, value: 2, counts: 2}
];
-
+ const expectedLayerDomain = {
+ domain: [7.13, 11],
+ aggregatedBins: {1: {i: 1, value: 7.13, counts: 2}, 2: {i: 2, value: 11, counts: 1}}
+ };
t.deepEqual(
spyLayerCallbacks.args[1][0],
- [7.13, 11],
+ expectedLayerDomain,
'should call onSetLayerDomain with correct domain'
);
t.deepEqual(
diff --git a/test/browser/layer-tests/hexagon-layer-specs.js b/test/browser/layer-tests/hexagon-layer-specs.js
index 3394463b9..4239fdcff 100644
--- a/test/browser/layer-tests/hexagon-layer-specs.js
+++ b/test/browser/layer-tests/hexagon-layer-specs.js
@@ -322,10 +322,13 @@ test('#HexagonLayer -> renderLayer', t => {
Object.keys(expectedProps).forEach(key => {
t.deepEqual(props[key], expectedProps[key], `should have correct props.${key}`);
});
-
+ const expectedLayerDomain = {
+ domain: [1, 2],
+ aggregatedBins: {1: {i: 1, value: 2, counts: 2}, 2: {i: 2, value: 1, counts: 1}}
+ };
t.deepEqual(
spyLayerCallbacks.args[0][0],
- [1, 2],
+ expectedLayerDomain,
'should call onSetLayerDomain with correct domain'
);
@@ -426,10 +429,13 @@ test('#HexagonLayer -> renderLayer', t => {
{i: 2, value: 1, counts: 1},
{i: 1, value: 2, counts: 2}
];
-
+ const expectedLayerDomain = {
+ domain: [7.13, 11],
+ aggregatedBins: {1: {i: 1, value: 7.13, counts: 2}, 2: {i: 2, value: 11, counts: 1}}
+ };
t.deepEqual(
spyLayerCallbacks.args[1][0],
- [7.13, 11],
+ expectedLayerDomain,
'should call onSetLayerDomain with correct domain'
);
t.deepEqual(
diff --git a/test/helpers/mock-state.js b/test/helpers/mock-state.js
index d6baf2005..1d5e752dd 100644
--- a/test/helpers/mock-state.js
+++ b/test/helpers/mock-state.js
@@ -899,6 +899,7 @@ export const expectedLoadedLayer0 = {
elevationScale: 5,
enableElevationZoomFactor: true,
fixedHeight: false,
+ // LAYER_VIS_CONFIGS.aggregation.defaultValue is AGGREGATION_TYPES.average,
colorAggregation: 'count',
sizeAggregation: 'count',
enable3d: false
diff --git a/test/node/utils/data-scale-utils-test.js b/test/node/utils/data-scale-utils-test.js
index 02d5bf5c7..e9fc4b051 100644
--- a/test/node/utils/data-scale-utils-test.js
+++ b/test/node/utils/data-scale-utils-test.js
@@ -2,7 +2,7 @@
// Copyright contributors to the kepler.gl project
import test from 'tape';
-
+import cloneDeep from 'lodash.clonedeep';
import {
getOrdinalDomain,
getQuantileDomain,
@@ -11,8 +11,10 @@ import {
createDataContainer,
getThresholdsFromQuantiles,
getDomainStepsbyZoom,
- getQuantLabelFormat
+ getQuantLabelFormat,
+ getHistogramDomain
} from '@kepler.gl/utils';
+import {StateWFilesFiltersLayerColor} from 'test/helpers/mock-state';
function numberSort(a, b) {
return a - b;
@@ -177,3 +179,33 @@ test('DataScaleUtils -> getQuantLabelFormat', t => {
t.end();
});
+
+test('DataScaleUtils -> getHistogramDomain', t => {
+ let aggregatedBins = [
+ {i: 0, value: 1, count: 1},
+ {i: 1, value: 2, count: 1},
+ {i: 2, value: 3, count: 1},
+ {i: 3, value: 4, count: 1}
+ ];
+ let histogramDomain = getHistogramDomain({aggregatedBins});
+
+ t.deepEqual(histogramDomain, [1, 4, 2.5]);
+
+ aggregatedBins = null;
+ histogramDomain = getHistogramDomain({aggregatedBins});
+
+ t.deepEqual(histogramDomain, [0, 0, 0]);
+
+ // test dataset
+ const InitialState = cloneDeep(StateWFilesFiltersLayerColor);
+ const {layers, datasets} = InitialState.visState;
+ const pointLayer = layers[0];
+ const dataset = datasets[pointLayer.config.dataId];
+ const field = dataset.fields[6];
+ const fieldValueAccessor = idx => dataset.getValue(field.name, idx);
+
+ histogramDomain = getHistogramDomain({dataset, fieldValueAccessor});
+ t.deepEqual(histogramDomain, [1, 12124, 912.2857142857143]);
+
+ t.end();
+});