Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(plugin-chart-echarts): add series sorting #23392

Merged
merged 4 commits into from
Mar 16, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
onlyTotalControl,
showValueControl,
richTooltipSection,
seriesOrderSection,
} from '../../controls';
import { AreaChartExtraControlsOptions } from '../../constants';

Expand Down Expand Up @@ -62,6 +63,7 @@ const config: ControlPanelConfig = {
label: t('Chart Options'),
expanded: true,
controlSetRows: [
...seriesOrderSection,
['color_scheme'],
[
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import {
import {
legendSection,
richTooltipSection,
seriesOrderSection,
showValueSection,
} from '../../../controls';

Expand Down Expand Up @@ -301,6 +302,7 @@ const config: ControlPanelConfig = {
label: t('Chart Options'),
expanded: true,
controlSetRows: [
...seriesOrderSection,
['color_scheme'],
...showValueSection,
[
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import {
import {
legendSection,
richTooltipSection,
seriesOrderSection,
showValueSection,
} from '../../../controls';

Expand Down Expand Up @@ -64,6 +65,7 @@ const config: ControlPanelConfig = {
label: t('Chart Options'),
expanded: true,
controlSetRows: [
...seriesOrderSection,
['color_scheme'],
[
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
import {
legendSection,
richTooltipSection,
seriesOrderSection,
showValueSection,
} from '../../../controls';

Expand All @@ -60,6 +61,7 @@ const config: ControlPanelConfig = {
label: t('Chart Options'),
expanded: true,
controlSetRows: [
...seriesOrderSection,
['color_scheme'],
...showValueSection,
[
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
import {
legendSection,
richTooltipSection,
seriesOrderSection,
showValueSectionWithoutStack,
} from '../../../controls';

Expand All @@ -60,6 +61,7 @@ const config: ControlPanelConfig = {
label: t('Chart Options'),
expanded: true,
controlSetRows: [
...seriesOrderSection,
['color_scheme'],
...showValueSectionWithoutStack,
[
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import { DEFAULT_FORM_DATA, TIME_SERIES_DESCRIPTION_TEXT } from '../constants';
import {
legendSection,
richTooltipSection,
seriesOrderSection,
showValueSection,
} from '../../controls';

Expand Down Expand Up @@ -60,6 +61,7 @@ const config: ControlPanelConfig = {
label: t('Chart Options'),
expanded: true,
controlSetRows: [
...seriesOrderSection,
['color_scheme'],
[
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,15 @@ import {
} from './types';
import {
DEFAULT_LEGEND_FORM_DATA,
DEFAULT_SORT_SERIES_DATA,
DEFAULT_TITLE_FORM_DATA,
} from '../constants';

// @ts-ignore
export const DEFAULT_FORM_DATA: EchartsTimeseriesFormData = {
...DEFAULT_LEGEND_FORM_DATA,
...DEFAULT_TITLE_FORM_DATA,
...DEFAULT_SORT_SERIES_DATA,
annotationLayers: sections.annotationLayers,
area: false,
forecastEnabled: sections.FORECAST_DEFAULT_DATA.forecastEnabled,
Expand Down Expand Up @@ -63,6 +65,8 @@ export const DEFAULT_FORM_DATA: EchartsTimeseriesFormData = {
onlyTotal: false,
percentageThreshold: 0,
orientation: OrientationType.vertical,
sort_series_type: 'sum',
sort_series_ascending: false,
};

export const TIME_SERIES_DESCRIPTION_TEXT: string = t(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,8 @@ export default function transformProps(
showLegend,
showValue,
sliceId,
sortSeriesType,
sortSeriesAscending,
timeGrainSqla,
timeCompare,
stack,
Expand Down Expand Up @@ -197,6 +199,8 @@ export default function transformProps(
stack,
totalStackedValues,
isHorizontal,
sortSeriesType,
sortSeriesAscending,
});
const showValueIndexes = extractShowValueIndexes(rawSeries, {
stack,
Expand Down Expand Up @@ -418,7 +422,7 @@ export default function transformProps(
forecastValue.sort((a, b) => b.data[yIndex] - a.data[yIndex]);
}

const rows: Array<string> = [`${tooltipFormatter(xValue)}`];
const rows: string[] = [];
const forecastValues: Record<string, ForecastValue> =
extractForecastValuesFromTooltipParams(forecastValue, isHorizontal);

Expand All @@ -435,6 +439,10 @@ export default function transformProps(
rows.push(`<span style="opacity: 0.7">${content}</span>`);
}
});
if (stack) {
rows.reverse();
}
rows.unshift(`${tooltipFormatter(xValue)}`);
return rows.join('<br />');
},
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
LabelPositionEnum,
LegendOrientation,
LegendType,
SortSeriesData,
} from './types';

// eslint-disable-next-line import/prefer-default-export
Expand Down Expand Up @@ -114,3 +115,8 @@ export const TOOLTIP_POINTER_MARGIN = 10;
// If no satisfactory position can be found, how far away
// from the edge of the window should the tooltip be kept
export const TOOLTIP_OVERFLOW_MARGIN = 5;

export const DEFAULT_SORT_SERIES_DATA: SortSeriesData = {
sort_series_type: 'sum',
sort_series_ascending: false,
};
43 changes: 42 additions & 1 deletion superset-frontend/plugins/plugin-chart-echarts/src/controls.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@ import {
ControlSetRow,
sharedControls,
} from '@superset-ui/chart-controls';
import { DEFAULT_LEGEND_FORM_DATA } from './constants';
import {
DEFAULT_LEGEND_FORM_DATA,
DEFAULT_SORT_SERIES_DATA,
} from './constants';
import { DEFAULT_FORM_DATA } from './Timeseries/constants';

const { legendMargin, legendOrientation, legendType, showLegend } =
Expand Down Expand Up @@ -212,3 +215,41 @@ export const richTooltipSection: ControlSetRow[] = [
[tooltipSortByMetricControl],
[tooltipTimeFormatControl],
];

const sortSeriesType: ControlSetItem = {
name: 'sort_series_type',
config: {
type: 'SelectControl',
freeForm: false,
label: t('Sort Series By'),
choices: [
['name', t('Category name')],
['sum', t('Total value')],
['min', t('Minimum value')],
['max', t('Maximum value')],
['avg', t('Average value')],
],
default: DEFAULT_SORT_SERIES_DATA.sort_series_type,
renderTrigger: true,
description: t(
'Based on what should series be ordered on the chart and legend',
),
},
};

const sortSeriesAscending: ControlSetItem = {
name: 'sort_series_ascending',
config: {
type: 'CheckboxControl',
label: t('Sort Series Ascending'),
default: DEFAULT_SORT_SERIES_DATA.sort_series_ascending,
renderTrigger: true,
description: t('Sort series in ascending order'),
},
};

export const seriesOrderSection: ControlSetRow[] = [
[<div className="section-header">{t('Series Order')}</div>],
[sortSeriesType],
[sortSeriesAscending],
];
7 changes: 7 additions & 0 deletions superset-frontend/plugins/plugin-chart-echarts/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,4 +167,11 @@ export interface TreePathInfo {
value: number | number[];
}

export type SortSeriesType = 'name' | 'max' | 'min' | 'sum' | 'avg';
villebro marked this conversation as resolved.
Show resolved Hide resolved

export type SortSeriesData = {
sort_series_type: SortSeriesType;
sort_series_ascending: boolean;
};

export * from './Timeseries/types';
112 changes: 83 additions & 29 deletions superset-frontend/plugins/plugin-chart-echarts/src/utils/series.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,18 @@ import {
AxisType,
} from '@superset-ui/core';
import { format, LegendComponentOption, SeriesOption } from 'echarts';
import { sumBy, meanBy, minBy, maxBy, orderBy } from 'lodash';
import {
AreaChartExtraControlsValue,
NULL_STRING,
TIMESERIES_CONSTANTS,
} from '../constants';
import { LegendOrientation, LegendType, StackType } from '../types';
import {
LegendOrientation,
LegendType,
SortSeriesType,
StackType,
} from '../types';
import { defaultLegendPadding } from '../defaults';

function isDefined<T>(value: T | undefined | null): boolean {
Expand Down Expand Up @@ -108,6 +114,46 @@ export function extractShowValueIndexes(
return showValueIndexes;
}

export function sortAndFilterSeries(
rows: DataRecord[],
xAxis: string,
extraMetricLabels: any[],
sortSeriesType?: SortSeriesType,
sortSeriesAscending?: boolean,
): string[] {
const seriesNames = Object.keys(rows[0])
.filter(key => key !== xAxis)
.filter(key => !extraMetricLabels.includes(key));

let aggregator: (name: string) => { name: string; value: any };

switch (sortSeriesType) {
case 'sum':
aggregator = name => ({ name, value: sumBy(rows, name) });
break;
case 'min':
aggregator = name => ({ name, value: minBy(rows, name)?.[name] });
break;
case 'max':
aggregator = name => ({ name, value: maxBy(rows, name)?.[name] });
break;
case 'avg':
aggregator = name => ({ name, value: meanBy(rows, name) });
break;
default:
aggregator = name => ({ name, value: name.toLowerCase() });
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that we're now sorting case insensitive (previously "Qwerty" would come before "abc")

break;
}

const sortedValues = seriesNames.map(aggregator);

return orderBy(
sortedValues,
['value'],
[sortSeriesAscending ? 'asc' : 'desc'],
).map(({ name }) => name);
}

export function extractSeries(
data: DataRecord[],
opts: {
Expand All @@ -118,6 +164,8 @@ export function extractSeries(
stack?: StackType;
totalStackedValues?: number[];
isHorizontal?: boolean;
sortSeriesType?: SortSeriesType;
sortSeriesAscending?: boolean;
} = {},
): SeriesOption[] {
const {
Expand All @@ -128,41 +176,47 @@ export function extractSeries(
stack = false,
totalStackedValues = [],
isHorizontal = false,
sortSeriesType,
sortSeriesAscending,
} = opts;
if (data.length === 0) return [];
const rows: DataRecord[] = data.map(datum => ({
...datum,
[xAxis]: datum[xAxis],
}));
const series = sortAndFilterSeries(
rows,
xAxis,
extraMetricLabels,
sortSeriesType,
sortSeriesAscending,
);

return Object.keys(rows[0])
.filter(key => key !== xAxis && key !== DTTM_ALIAS)
.filter(key => !extraMetricLabels.includes(key))
.map(key => ({
id: key,
name: key,
data: rows
.map((row, idx) => {
const isNextToDefinedValue =
isDefined(rows[idx - 1]?.[key]) || isDefined(rows[idx + 1]?.[key]);
const isFillNeighborValue =
!isDefined(row[key]) &&
isNextToDefinedValue &&
fillNeighborValue !== undefined;
let value: DataRecordValue | undefined = row[key];
if (isFillNeighborValue) {
value = fillNeighborValue;
} else if (
stack === AreaChartExtraControlsValue.Expand &&
totalStackedValues.length > 0
) {
value = ((value || 0) as number) / totalStackedValues[idx];
}
return [row[xAxis], value];
})
.filter(obs => !removeNulls || (obs[0] !== null && obs[1] !== null))
.map(obs => (isHorizontal ? [obs[1], obs[0]] : obs)),
}));
return series.map(name => ({
id: name,
name,
data: rows
.map((row, idx) => {
const isNextToDefinedValue =
isDefined(rows[idx - 1]?.[name]) || isDefined(rows[idx + 1]?.[name]);
const isFillNeighborValue =
!isDefined(row[name]) &&
isNextToDefinedValue &&
fillNeighborValue !== undefined;
let value: DataRecordValue | undefined = row[name];
if (isFillNeighborValue) {
value = fillNeighborValue;
} else if (
stack === AreaChartExtraControlsValue.Expand &&
totalStackedValues.length > 0
) {
value = ((value || 0) as number) / totalStackedValues[idx];
}
return [row[xAxis], value];
})
.filter(obs => !removeNulls || (obs[0] !== null && obs[1] !== null))
.map(obs => (isHorizontal ? [obs[1], obs[0]] : obs)),
}));
}

export function formatSeriesName(
Expand Down
Loading